首先安装C++的Protobuf,按官方指导来: https://github.com/protocolbuffers/protobuf/tree/master/src
下载release包,解压后编译安装即可。
用法举例,先定义proto文件:
syntax = "proto3";
package test;
enum Sex {
BOY = 0;
GIRL = 1;
}
message Student {
int32 Id = 1; // id
string Name = 2; // name
Sex Sex = 3;
}
message Team {
int32 Id = 1;
string Name = 2;
repeated Student Student = 3;
}
然后用protoc生成对应的编解码文件: protoc --cpp_out=. test.proto
,cpp_out表示生成cpp的编解码源文件。测试代码:
#include <iostream>
#include <string>
#include "test.pb.h"
using namespace std;
using namespace test;
int main()
{
Team team;
team.set_id(1);
team.set_name("Rocket");
Student *s1 = team.add_student(); // 添加repeated成员
s1->set_id(1);
s1->set_name("Mike");
s1->set_sex(BOY);
Student *s2 = team.add_student();
s2->set_id(2);
s2->set_name("Lily");
s2->set_sex(GIRL);
// encode --> bytes stream
string out;
team.SerializeToString(&out);
// decode --> team structure
Team t;
t.ParseFromArray(out.c_str(), out.size()); // or parseFromString
cout << t.DebugString() << endl;
for (int i = 0; i < t.student_size(); i++) {
Student s = t.student(i); // 按索引解repeated成员
cout << s.name() << " " << s.sex() << endl;
}
return 0;
}
编译的时候记得链接protobuf库。Protobuf还是挺好用的。