初识protobuf
2016-02-22 13:04
501 查看
这里(IBM)给出了protobuf的基本介绍和原理
http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/安装
开始按照上面IBM给出的文档安装了protobuf3.0版本,但是装完后生成的 .pb.cc 和 .pb.h 代码无法编译链接。不知道是静态链接库的问题还是源码包的问题。于是按照下面这篇博客成功安装了 protobuf2.6.1 。http://www.cnblogs.com/javaee6/p/4849051.html
2.6.1 源码包
https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz测试实例
lm.test.protopackage lm; message test { required int32 id=1; required string str=2; }
将上面定义的数据格式生成c++代码
命令: protoc -I=. –cpp_out=. lm.test.proto生成了lm.test.pb.h 和 lm.test.pb.cc 文件。
编写main.cpp 测试
IBM 给的例子是将proto格式的消息放到了fstream流中,但是如果需要在网络中传输时,需要转化为字符串。于是,我写了下面的例子。//main.cpp #include<iostream> #include<string> #include"lm.test.pb.h" using namespace std; //输出解析后的消息 void ListMsg(const lm::test &msg) { cout<<msg.id()<<endl; cout<<msg.str()<<endl; } int main() { lm::test msg1; msg1.set_id(100); //id msg1.set_str("hello"); string tmp; //序列化转string msg1.SerializePartialToString(&tmp); lm::test msg2; //string反序列化 if(msg2.ParseFromString(tmp)) { ListMsg(msg2); } else { cout<<"Parse error!"<<endl; } return 0; }
编译链接 (需要加静态链接库 libprotobuf.a , 命令如下)
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- android Google Map获取地理位置信息的方法
- 谷歌 Project Zero 团队宣布新政策,漏洞披露前将有完整的 90 天缓冲期
- 关于指针的一些事情
- Android使用Google Map浅谈
- 专家解读:开源软件项目是否会被限制出口?
- 专家解读:开源软件项目是否会被限制出口?
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Google排名算法改变 不在以外部链为主
- Google Adsense 支票托收信息收集 (1-30-2007)
- Google Adsense常用技巧总结
- Google推广的十二点技巧
- google优化圣经做网站必备第1/3页
- Google AdSense英文高价关键词排行列表
- Google 统计图表(Flash)小插件
- 2月份停止Google Adsense下线推介 将在中国地区停止投放
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本