protocol buffer 安装与使用
1、下载protocol buffer
测试版本:protobuf-2.5.0.tar.gz
2、解压并安装,执行以下命令
tar -zxvf protobuf-2.5.0.tar.gz
./configure
make check
make install
3、书写 .proto文件
package lm;
message helloworld
{
required int32 id = 1;
required string str = 2 ;
optional int32 opt = 3;
}//这是proto2的书写规则,如果需要使用grpc则应使用proto3的书写规则,参考网址https://developers.google.com/protocol-buffers/docs/proto3#simple
编译形成 .cc、.h文件,执行命令:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
假设 proto 文件存放在 $SRC_DIR 下面,您也想把生成的文件放在同一个目录下
如图:
4、编写writer和reader文件
writer文件:
#include "test.pb.h"
#include <iostream>
#include <fstream>
using namespace std ;
int main(void)
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
// Write the new address book back to disk.
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output)) {
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
reader文件:
#include "test.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
void ListMsg(const lm::helloworld & msg) {
cout << msg.id() << endl;
cout << msg.str() << endl;
}
int main(int argc, char* argv[]) {
lm::helloworld msg1;
{
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
ListMsg(msg1);
}
5、编译运行,形成writer,reader等exe文件
g++ test.pb.cc writer.cc -o writer -lprotobuf
g++ test.pb.cc reader.cc -o reader -lprotobuf
执行writer,执行reader,结果如图: