protobuf使用
编写结构
// Filename: person.proto
syntax="proto3";
package person;
message Person {
string name = 1;
int32 id = 2;
uint32 age = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
repeated PhoneNumber phone = 4;
}
生成C++文件
$ protoc -I=. --cpp_out=. person.proto
$ ls
person.pb.cc person.pb.h person.proto
编写例子
#include <iostream>
#include <iomanip>
#include "person.pb.h"
int main()
{
person::Person person;
person.set_name("furong");
person.set_id(1);
person.set_age(10);
person::Person_PhoneNumber *phone = person.add_phone();
phone->set_number("010-110");
phone = person.add_phone();
phone->set_number("130-1234-5678");
phone->set_type(person::Person::WORK);
std::cout << "number = " << phone->number() << std::endl;
phone->clear_number();
uint32_t size = person.ByteSize();
unsigned char byteArray[size];
person.SerializeToArray(byteArray, size);
for (int i = 0; i < size; i++)
{
std::cout << std::hex << std::setiosflags(std::ios::uppercase) << std::setfill('0') << std::setw(2) << static_cast<int>(byteArray[i]) << ' ';
}
std::cout << std::endl;
person::Person parse_person;
parse_person.ParseFromArray(byteArray, size);
std::cout << "*****************************" << std::endl;
std::cout << "id: " << parse_person.id() << std::endl;
std::cout << "name: " << parse_person.name() << std::endl;
std::cout << "age: " << std::dec << parse_person.age() << std::endl;
for (int i = 0; i < parse_person.phone_size(); i++)
{
const person::Person_PhoneNumber &phone = parse_person.phone(i);
std::cout << "phone_type: " << phone.type() << std::endl;
std::cout << "phone_number: " << phone.number() << std::endl;
}
std::cout << "*****************************" << std::endl;
return 0;
}
编译运行
$ g++ main.cpp person.pb.cc -I include -L lib -lprotobuf
$ ./a.out
number = 130-1234-5678
0A 06 66 75 72 6F 6E 67 10 01 18 0A 22 09 0A 07 30 31 30 2D 31 31 30 22 02 10 02
*****************************
id: 1
name: furong
age: 10
phone_type: 0
phone_number: 010-110
phone_type: 2
phone_number:
*****************************