现在的位置: 首页 > 综合 > 正文

google proto buffer使用

2013年10月23日 ⁄ 综合 ⁄ 共 1919字 ⁄ 字号 评论关闭

听说google proto buffer(以下简称protobuf)已经很久了,但是一直没有尝试使用它。其中一个原因是,项目组自己写了个打包和解包的工具,而且代码也简单,可以很方便的扩展到自动生成xml之类的配置文件,已经能很好的符合项目的需要。但是最近发现protobuf有个很不错的功能,就是可以向已有的协议中添加新的字段,而不影响采用旧协议的服务。所以就想试试protobuf。

 

  要使用google proto buffer,首先要进行的就是安装,先说说我的(mac os X 10.7.2)安装过程吧:

  1、下载google proto buff。

  2、解压下载的包,并且阅读README.txt,根据里面的指引进行安装。

  3、 $ ./configure

    $ make

    $ make check
    $ make install

    没有意外的话,前面三步应该都能顺利完成,第四步的时候,需要root权限。我采用的默认的路径,所以,仅仅用root权限,还是安装不了,要自己先在/usr/local下新建一个lib的目录,然后执行make install,这样,应该就能顺利安装google proto buffer了。

 验证:
查看是否安装成功:protoc --version
如果出现:libprotoc 2.5.0 则说明安装成功!
如果出现错误:

protoc: error while loading shared libraries: libprotobuf.so.0: cannot open
shared object file: No such file or directory
The issue is that Ubuntu 8.04 doesn't include /usr/local/lib in
library paths.
 
  To fix it for your current terminal session, just type in
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

  安装完后,先写一个测试程序来测试下安装,先来看看proto文件:

View Code 
 package hello;
 
 message Hello{
     required int32      id      = 1;        //user id
     required string     name    = 2;        //user name
     optional string     email   = 3;        //user email
 }

接着,要用protoc生成一个对应的类,我把它生成在./out目录里:

  protoc hello.proto --cpp_out=./out

  接下来,在out目录下,会生成两个文件:

  $> ls

  hello.pb.cc hello.pb.h  

 

  接下来,编写测试用的c++代码:

hello.cc
 #include <stdio.h>
 #include <string.h>
 
 #include "out/hello.pb.h"
 
 using namespace std;
 using namespace hello;
 
 int main()
 {
     Hello a;
     a.set_id(101);
     a.set_name("huangwei");
 
     string tmp;
     bool ret = a.SerializeToString(&tmp);
     if (ret) 
     {
         printf("encode success!\n");
     }
     else 
     {
         printf("encode faild!\n");
     }
 
     Hello b;
 
     ret = b.ParseFromString(tmp);
     if (ret)
     {
         printf("decode success!\n id= %d \n name = %s\n", b.id(), b.name().c_str());
     }
     else
     {
         printf("decode faild!\n");
     }
 
     return 0;
 }

接着,编译一下这个代码,由于使用了protobuf的库,所以编译的时候,要把这些库也链接进来:

   g++ hello.cc ./out/hello.pb.cc -o hello -I./out -I/usr/local/protobuf/include -L/usr/local/lib -lprotobuf

 

  这样,就生成了测试程序。

  运行一下:

  $> ./hello
  encode success!
  decode success!
  id= 101
  name = huangwei

 

  这样,简单的google proto buffer的使用就完成了。有什么错误的地方,还请各位斧正。

 

 转自: http://www.cnblogs.com/huangwei/archive/2012/01/16/2324108.html

抱歉!评论已关闭.