[Google Protocol Buffer API简单使用总结]
大致步骤如下:
1、编写“msg.proto”文件
package lm;//我理解成命名空间
message helloworld//我理解成类
{
required int32 id=1;//必选类型,每条消息中都必须包含此域
required string str=2;
optional int32 opt=3;//可选类型,每条消息可包含也可不包含
//repeated 重复类型,每条消息包含零个或任意个次域
}
2、生成protocobuf的引用文件
protoc --cpp_out=. msg.proto//它会在当前目录下会生成两个C++文件
3、编写序列化文件write.cc,调用第二步生成的C++文件进行序列化操作
#include "msg.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
int main(void)
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output)) {//序列化
std::cerr << "Failed to write msg." <<std::endl;
return -1;
}
return 0;
}
4、编译write.cc,生成可执行文件,命令为
g++ msg.pb.cc write.cc -o write -I/user/local/lib/protobuf/include -lprotobuf -lpthread
5、编写反序列化文件reader.cc,调用第二步生成的C++文件进行反序列化操作
#include "msg.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
using namespace lm;
void listmsg(const lm::helloworld & msg)
{
std::cout <<msg.id()<<std::endl;
std::cout <<msg.str()<<std::endl;
}
int main(void)
{
lm::helloworld msg1;
fstream input("./log",ios::in | ios::binary);
if(!msg1.ParseFromIstream(&input))//反序列化
{
std::cerr<< "Failed to prase address book"<<std::endl;
return -1;
}
listmsg(msg1);
return 0;
}
6、编译reader.cc,生成可执行文件,命令为
g++ msg.pb.cc reader.cc -o reader -I/user/local/lib/protobuf/include -lprotobuf -lpthread
7、设置环境变量
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH/*这一步很重要,没有设置环境变量将不能之星序列化可执行文件*/
8、执行可执行文件write
./write
9、执行可执行文件reader
./reader