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.测试程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #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
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步