一、簡介
ProtocolBuffer是用于結(jié)構(gòu)化數(shù)據(jù)串行化的靈活、高效、自動的方法,有如XML,不過它更小、更快、也更簡單。你可以定義自己的數(shù)據(jù)結(jié)構(gòu),然后使用代碼生成器生成的代碼來讀寫這個數(shù)據(jù)結(jié)構(gòu)。你甚至可以在無需重新部署程序的情況下更新數(shù)據(jù)結(jié)構(gòu)。
二、特點
ProtocolBuffer擁有多項比XML更高級的串行化結(jié)構(gòu)數(shù)據(jù)的特性,ProtocolBuffer:
· 更簡單
· 小3-10倍
· 快20-100倍
· 更少的歧義
· 可以方便的生成數(shù)據(jù)存取類
例如,讓我們看看如何在XML中建模Person的name和email字段:
<person>
<name>John Doe</name>
<email>jdoe@example.com</email>
</person>
對應(yīng)的ProtocolBuffer報文則如下:
#ProtocolBuffer的文本表示
#這不是正常時使用的二進制數(shù)據(jù)
person {
name: "John Doe"
email: "jdoe@example.com"
}
三、開發(fā)步驟
1、下載包( http://code.google.com/p/protobuf/downloads/ ),包含了Java、Python、C++的ProtocolBuffer編譯器,用于生成你需要的IO類。構(gòu)建和安裝你的編譯器,跟隨README的指令就可以做到。
一旦你安裝好了,就可以跟著編程指導(dǎo)( http://code.google.com/apis/protocolbuffers/docs/tutorials.html )來選擇語言-隨后就是使用ProtocolBuffer創(chuàng)建一個簡單的應(yīng)用了。
2、創(chuàng)建. proto文件,文件中定義你需要做串行化的數(shù)據(jù)結(jié)構(gòu)信息,下面定義個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生成對應(yīng)的C++文件,在CMD命令框中輸入如下命令(路徑根據(jù)實際情況修改):
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;
// 顯示調(diào)式報文
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;
}