Protobuf总结

来源:互联网 发布:官方原版windows xp 编辑:程序博客网 时间:2024/05/21 19:40

1:Protocol Buffer简介
Protocol Buffer(PB)是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。可用于通讯软件中与语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python,C#,lua 五种语言的 API。

2:Protocol Buffer优点
支持多种语言;使用简单;具有“向后”兼容性;pb不管是处理时间上,还是空间占用上都优于现有的其他序列化方式

3:下载pb源代码:我用的是protobuf-2.6.1
下载完毕后打开protobuf.sln,
打开protobuf.sln
对protoc进行编译
这里写图片描述
编译成功后打开Dedug目录,会看到生成了libprotoc.lib和protoc.exe。
4:编写proto协议
将protoc.exe拷贝出来,建立两个文件夹,
这里写图片描述
在src中定义消息
这里写图片描述
在test.proto中定义协议 (之后会介绍)

message test{    required int32 id=1;   required string name=2;}

5:生成Pb类
接下来我们编写一个批处理文件gen.bat
这里写图片描述
cd E:\proto
protoc.exe -I=./src –cpp_out=./dst ./src/test.proto
运行gen.bat后,会在dst文件夹中生成test.pb.h与test.pb.cc
6:在项目中引用Pb类
我们新建一个项目,将test.pb.h与test.pb.cc添加进来。
c/c++->常规->附加包含目录->E:\protobuf-2.6.1\testProto\src;
c/c++->常规->附加包含目录->E:\protobuf-2.6.1\src
链接器->常规->附加库目录->E:\protobuf-2.6.1\vsprojects\Debug
链接器->输入->附加依赖项->libprotobuf.lib
7:使用PB序列化类和反序列化PB类对象

#include "test.pb.h"#include <iostream>using namespace std;void main(){    test l;    l.set_id(100);    l.set_name("asdfgfg");    const string s = l.SerializeAsString();    test l1;    l1.ParseFromString(s);    cout << l1.id() << endl;    cout << l1.name() << endl;    getchar();}

“`
结果输出:
这里写图片描述

0 0