首先安装C++的Protobuf,按官方指导来: https://github.com/protocolbuffers/protobuf/tree/master/src
下载release包,解压后编译安装即可。
用法举例,先定义proto文件,如何定义protobuf网上有很多教程:
syntax = "proto3";
//实际使用中一般把package注释掉
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生成对应的编解码文件:
// c++文件生成命令 protoc --cpp_out=./ ./xxx.proto
// java文件生成命令 protoc --java_out=./ ./xxx.proto
//python文件生成命令 protoc --python_out=./ ./xxx.proto
#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);
//或者
int length=team.ByteSize();
char* buf=new char[length];
team.SerializeToArray(buf,length);
// decode --> team structure
Team t;
t.ParseFromArray(out.c_str(), out.size()); // or parseFromString,如果该出是使用ParseFromArray,上面也是应该对应
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;
}
注意:引用头文件时候注意顺序,容易出差
常用的序列化和反序列化的方法有
bool SerializeToArray(char* buf,int size) const;把message编码进数组buf.
bool ParseFromArray(const char* buf,int size);把buf解码到message。
bool SerializeToString(string* output) const;把message编码进output。
bool ParseFromString(const string& data);从string解码到message
bool SerializeToArray(char* buf,int size) const;把message编码进数组buf.
bool ParseFromArray(const char* buf,int size);把buf解码到message。
bool SerializeToOstream(ostream* output) const;把message编码进ostream
bool ParseFromIstream(istream* input);从istream解码到message