Protocol Buffers安装与简单使用

来源:互联网 发布:javamail smtp 端口 编辑:程序博客网 时间:2024/04/28 06:41


转载:

http://blog.sina.com.cn/s/blog_740ccd040101hf3z.html



ProtocolBuffers是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。现阶段支持C++、JAVA、Python等三种编程语言。

1、什么是Protocol Buffers
ProtocolBuffer是用于结构化数据串行化的灵活、高效、自动的方法,有如XML,不过它更小、更快、也更简单。你可以定义自己的数据结构,然后使用代码生成器生成的代码来读写这个数据结构。你甚至可以在无需重新部署程序的情况下更新数据结构。

2、Protocol Buffers的特点

更简单

数据描述文件只需原来的1/10至1/3

解析速度是原来的20倍至100倍

减少了二义性

生成了更容易在编程中使用的数据访问类



3、Protocol Buffers安装配置

从http://code.google.com/p/protobuf/downloads/list下载

然后./configure   make   makeinstall

安装完毕

ps:./configure 出现这样的


出现下面的错误
configure: error: C++ preprocessor "/lib/cpp" fails sanitycheck
See `config.log' for more details

这个在ubuntu很常见,这次干脆一下子把常用的库全部下载来
root@ubuntu:/opt/protocbuf/protobuf-2.5.0# apt-get installbuild-essential
到最后可以看到
正在处理用于 man-db 的触发器...
正在设置 libtimedate-perl (1.2000-1) ...
正在设置 libdpkg-perl (1.16.1.2ubuntu7.1) ...
正在设置 dpkg-dev (1.16.1.2ubuntu7.1) ...
正在设置 libalgorithm-diff-perl (1.19.02-2) ...
正在设置 libalgorithm-diff-xs-perl (0.04-2build2) ...
正在设置 libalgorithm-merge-perl (0.08-2) ...
正在设置 libstdc++6-4.6-dev (4.6.3-1ubuntu5) ...
正在设置 g++-4.6 (4.6.3-1ubuntu5) ...
正在设置 g++ (4:4.6.3-1ubuntu5) ...
update-alternatives: 使用 /usr/bin/g++ 来提供 /usr/bin/c++ (c++),于自动模式 中。
正在设置 build-essential (11.5ubuntu2.1) ...

g++处理器已经加入来了
再次配置就没问题了。


运行protoc --version
protoc: error while loading shared libraries:libprotobuf.so.7: cannot open shared object file: No such file ordirectory 




是因为系统找不到lib库 root@roson-vm:/home/protobuf# gedit /etc/ld.so.conf修改如下: include /etc/ld.so.conf.d/*.conf /usr/local/lib 然后ldconfig更新库文件路径

现在运行protoc--version就正常了
root@roson-vm:/home/protobuf# protoc --version
libprotoc 2.5.0

4、使用
新建proto文件gedit test.proto,如下:
package test;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}

调用protoc编译器编译接口文件
root@roson-vm:/home/protobuf# protoc test.proto--cpp_out=prototest/
C++用--cpp_out输出,prototest是输出目录
其他语言可以用protoc --help






编写测试程序
root@roson-vm:/home/protobuf# gedit test.cpp
#include "prototest/test.pb.h"
#include <stdio.h>
int main()
{
using namespace test;
Person p;
p.set_name("roson");
p.set_id(1);
p.set_email("roson@danale.com");
std::string str;
p.SerializeToString(&str); // 将对象序列化到字符串
printf("%s\n",str.c_str());
Person test;
test.ParseFromString(str); // 从字符串反序列化
printf("test.email=%s\n", test.email().c_str()); //输出将是roson,说明反序列化正确
return 0;
}

编译:
root@roson-vm:/home/protobuf#g++ -o prototest test.cpp prototest/test.pb.cc-lprotobuf

运行
root@roson-vm:/home/protobuf# ./test

输出:







其中中间的是二进制数字来,这个先不用考虑,可以看到数据正常输出。










0 0
原创粉丝点击