1.Protocol Buffers簡介
Protocol Buffers (ProtocolBuffer/ protobuf )是Google公司開發的一種數據描述語言,類似於XML能夠將結構化數據序列化,可用於數據存儲、通信協議等方面。現階段支持C++、JAVA、Python等三種編程語言。
2.protobuf相比Xml的優點
•更簡單
•數據描述文件只需原來的1/10至1/3
•解析速度是原來的20倍至100倍
•減少了二義性
•生成了更容易在編程中使用的數據訪問類
3.安裝
yum -y install protobuf-compiler protobuf-static protobuff protobuf-devel
4.使用
vi helloworld.proto
輸入下面的數據:
message helloworld {
required int32 id = 1; // ID
required string str = 2; // str
}
5.編譯 .proto
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/helloworld.proto
protoc -I=. --cpp_out=. ./helloworld.proto
命令將生成:
helloworld.pb.h , 定義了 C++ 類的頭文件
helloworld.pb.cc , C++ 類的實現文件
6.測試程序
#include "helloworld.pb.h" //包含生成的頭文件
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
helloworld msg;
msg.set_id(101);
msg.set_str("hello");
// 序列化消息
char buff[1024] = {0};
msg.SerializeToArray(buff, 1024);
//解析消息
helloworld msgread;
msgread.ParseFromArray(buff, 1024);
cout << msgread.id() << endl;
cout << msgread.str() << endl;
}
7.編譯運行
g++ -o main main.cpp helloworld.pb.cc -lprotobuf -lpthread
./main
