Posted on 2012-04-13 11:25
chugf 閱讀(8485)
評論(2) 編輯 收藏 引用
一、簡介
ProtocolBuffer是用于結構化數據串行化的靈活、高效、自動的方法,有如XML,不過它更小、更快、也更簡單。你可以定義自己的數據結構,然后使用代碼生成器生成的代碼來讀寫這個數據結構。你甚至可以在無需重新部署程序的情況下更新數據結構。
二、特點
ProtocolBuffer擁有多項比XML更高級的串行化結構數據的特性,ProtocolBuffer:
· 更簡單
· 小3-10倍
· 快20-100倍
· 更少的歧義
· 可以方便的生成數據存取類
例如,讓我們看看如何在XML中建模Person的name和email字段:
<person>
<name>John Doe</name>
<email>jdoe@example.com</email>
</person>
對應的ProtocolBuffer報文則如下:
#ProtocolBuffer的文本表示
#這不是正常時使用的二進制數據
person {
name: "John Doe"
email: "jdoe@example.com"
}
三、開發步驟
1、下載包( http://code.google.com/p/protobuf/downloads/ ),包含了Java、Python、C++的ProtocolBuffer編譯器,用于生成你需要的IO類。構建和安裝你的編譯器,跟隨README的指令就可以做到。
一旦你安裝好了,就可以跟著編程指導( http://code.google.com/apis/protocolbuffers/docs/tutorials.html )來選擇語言-隨后就是使用ProtocolBuffer創建一個簡單的應用了。
2、創建. proto文件,文件中定義你需要做串行化的數據結構信息,下面定義個Order. Proto:
package xquant;
option java_package = "com.xquant";
option java_outer_classname = "Order";
message Order {
required int32 action = 1;
required string serialNo = 2;
required string version = 3;
optional string operator = 4;
required string code = 5;
required string name = 6;
required string price = 7;
required string amount = 8;
}
3、使用google的protoc.exe生成對應的C++文件,在CMD命令框中輸入如下命令(路徑根據實際情況修改):
F:\projects\c++\protobuf-2.4.1\examples>protoc --cpp_out=F:\projects\c++\protobu
f-2.4.1\examples order.proto
生成文件:
order.pb.h
order.pb.cc
4、新建C++工程Demo,把order.pb.h和order.pb.cc加入工程中,添加lib庫
# pragma comment(lib, "libprotobuf.lib")
代碼如下:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include "order.pb.h"
using namespace std;
void initOrder(xquant::Order* order) {
order->set_action(100);
order->set_serialno("100abc");
order->set_version("1.00.003");
string code = "TF0001";
order->set_code(code);
string name = "test";
order->set_name(name);
order->set_price("10.01");
order->set_amount("10000000.00");
}
int _tmain(int argc, _TCHAR* argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
// 組裝報文
xquant::Order order;
initOrder(&order);
// 對象序列化為string
string order_str;
order.SerializeToString(&order_str);
cout << order_str << endl;
// 顯示調式報文
string order_debug = order.DebugString();
cout << order_debug << endl;
// string反序列化為對象
xquant::Order order_2;
order_2.ParseFromString(order_str);
cout << order_2.code() << endl;
cout << order_2.name() << endl;
google::protobuf::ShutdownProtobufLibrary();
getchar();
return 0;
}