初识protobuf

这里(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 , 命令如下)

这里写图片描述

这里写图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值