您的位置:首页 > 编程语言 > C语言/C++

初识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.proto

package 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 , 命令如下)



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  google protobuf c++