C++中使用protobuf
环境:
protobuf: v27.3(2024-08-01)
abseil: 20240722.0
1. 下载源码
git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
2. 编译源码
# configure shared lib
cmake -DCMAKE_CXX_STANDARD=14 -DCMAKE_INSTALL_PREFIX=install -Dprotobuf_BUILD_SHARED_LIBS=ON -B build
# compile
cmake --build build --config Release
# install
cmake --install build --config Release
install目录结构
tree
.
+--- bin
| +--- abseil_dll.dll
| +--- libprotobuf-lite.dll
| +--- libprotobuf.dll
| +--- libprotoc.dll
| +--- protoc-gen-upb.exe
| +--- protoc-gen-upbdefs.exe
| +--- protoc-gen-upb_minitable.exe
| +--- protoc.exe
+--- cmake
+--- include
+--- lib
3. 编写通讯录addressbook.proto
syntax = "proto3";
package com.test;
message Person {
string name = 1;
int32 age = 2;
string phone = 3;
}
message AddressBook{
repeated Person people = 1;
}
4. 编译
protoc -I=. --cpp_out=. addressbook.proto
tree
.
+--- addressbook.pb.cc
+--- addressbook.pb.h
+--- addressbook.proto
+--- protoc.exe
5. C++中使用
main.cpp
#include <iostream>
#include "addressbook.pb.h"
using namespace com::test;
void printfAddressBook(const AddressBook& addressbook, const char* str = "")
{
for (int i = 0; i < addressbook.people_size(); ++i)
{
const Person& person = addressbook.people(i);
printf("%s - name: %s, age: %d, phone: %s\n", str, person.name().c_str(), person.age(), person.phone().c_str());
}
}
int main(int argc, char *argv[])
{
AddressBook addressbook1;
Person* person1 = addressbook1.add_people();
person1->set_name("xiaoming");
person1->set_age(30);
person1->set_phone("13012345678");
Person* person2 = addressbook1.add_people();
person2->set_name("xiaohong");
person2->set_age(31);
person2->set_phone("13112345678");
printfAddressBook(addressbook1, "AddressBook");
// Serialize
std::string serializeData = addressbook1.SerializeAsString();
std::cout << "SerializeAsString - " << serializeData.c_str() << std::endl;
// Parse
AddressBook addressbook2;
addressbook2.ParseFromString(serializeData);
printfAddressBook(addressbook2, "ParseFromString");
getchar();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(main)
include_directories(.) # addressbook.pb.h
# protobuf
add_definitions(-DPROTOBUF_USE_DLLS)
include_directories(include)
link_directories(lib)
add_executable(${PROJECT_NAME} main.cpp addressbook.pb.cc)
target_link_libraries(${PROJECT_NAME} libprotobuf abseil_dll)
目录结构
tree
.
+--- include
+--- lib
+--- addressbook.pb.cc
+--- addressbook.pb.h
+--- addressBook.proto
+--- CMakeLists.txt
+--- main.cpp
6. 结果
AddressBook - name: xiaoming, age: 30, phone: 13012345678
AddressBook - name: xiaohong, age: 31, phone: 13112345678
SerializeAsString -
xiaoming13012345678
xiaohong13112345678
ParseFromString - name: xiaoming, age: 30, phone: 13012345678
ParseFromString - name: xiaohong, age: 31, phone: 13112345678