protobuf初探
来源:互联网 发布:武汉矩阵互动科技抄袭 编辑:程序博客网 时间:2024/06/10 00:24
Protobuf是google的一个开源编解码协议,主要用于协议过程中的编解码包,对比与XML与JSON等方式,具有以下优势:
- 灵活,支持语言描述。
- 精简,效率高,二进制编解码。
- 支持多种语言的生成,支持跨平台。
- 支持动态扩展。
项目主页:http://code.google.com/p/protobuf/
下载:http://code.google.com/p/protobuf/downloads/list protobuf-2.4.1.tar.gz
安装步骤:
- 下载protobuf-2.4.1.tar.gz
- 解压
- ./configure
- make
- make install
然后,在/usr/lib/include以及/usr/local/lib下将安装相应的头文件以及.a,.so等库文件。
编写proto协议描述文件:
package corey; message helloworld { required int32 id = 1; required string name = 2; optional int32 gender = 3; }
利用protoc命令行工具生成响应的.h.cc文件:
protoc ./helloworld.proto --cpp_out=./
相应目录下(当前目录)出现:
helloworld.pb.cc helloworld.pb.h
编写测试用例:
#include <helloworld.pb.h> #include <stdio.h> #include <stdlib.h> #include <fstream> using namespace std; using namespace corey; int main(int argc,char** argv){ helloworld hw; /* hw.set_gender(1); hw.set_id(33); hw.set_name("hello wrld"); printf("hello world\n"); fstream output("./helloworld.bin",ios::out|ios::trunc|ios::binary); if(!hw.SerializeToOstream(&output)){ printf("error\n"); } */ fstream input("./helloworld.bin",ios::in|ios::binary); hw.ParseFromIstream(&input); printf("%d,%d,%s",hw.id(),hw.gender(),hw.name().c_str()); return 0; }
编译:g++ helloworld.c helloworld.pb.cc -o ./helloworld -I./ -lprotobuf
分别将helloworld对象进行了序列化写入文件,读取文件反序列的操作,如果helloworld的required属性没有设置响应的值,则会产生:
libprotobuf ERROR google/protobuf/message_lite.cc:123] Can't parse message of type "corey.helloworld" because it is missing required fields: id, name
- protobuf初探
- ProtoBuf 初探
- protobuf 初探
- protobuf的使用初探
- Android Protobuf 初探笔记
- protobuf
- ProtoBuf
- protobuf
- protobuf
- protobuf
- Protobuf
- protobuf
- Protobuf
- protobuf
- protobuf
- protobuf
- protobuf
- protobuf
- 5.windbg script-禁用IsDebuggerPresent(调试 kernel32!SetUnhandledExceptionFilter)
- hive的插入操作
- 关于like的优化思考
- android 项目导入错误解决方法收集
- Warning: Cannot modify header information - headers already sent by (output started at...
- protobuf初探
- __extension__ typedef int __ssize_t;是什么意思
- vs2005无法打开工程
- dll的概念、dll导出类(转)
- 【框架-MFC】CMFCMenuBar 菜单按钮的图标添加
- 算法:将table标识的树形结构文本数据快速导入Mysql邻接表
- 深入探索linux系统的启动流程
- 第三方类库C语言运行时链接研究
- 如何让latex中插入没有标号的footnote