使用指南可以看這篇文章介紹:
http://www.shnenglu.com/liquidx/
下載Protocol Buffers:
http://code.google.com/p/protobuf/downloads/list
在vc環境下使用則在解壓縮文件中有一個vsprojects文件夾, 使用vs來編譯出libprotobuf.lib,libprotoc.lib
設置你的擴展頭文件包含目錄為 "D:\protobuf-2.1.0\src"
按照指南, 首先我們定義一個test.proto文件內容如下:
package Test;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
然后用protoc編譯器編譯出c++模塊, 這里有一個已經編譯好的編譯器, 你也可以從壓縮包中的源代碼編譯出該編譯器.
http://protobuf.googlecode.com/files/protoc-2.1.0-win32.zip
用這個指令編譯
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
然后我們得到了
test.pb.h
test.pb.cc
2個c++文件
現在我們可以在項目中使用它了:
#include <iostream>
#include "test.pb.h"
#include <fstream>
#pragma comment( lib, "libprotobuf.lib" )
#pragma comment( lib, "libprotoc.lib" )
int _tmain(int argc, _TCHAR* argv[])
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// 設置數據, 并序列化到文件
Test::Person person;
person.set_id( 123 );
person.set_name( "liquidx" );
person.set_email( "liquidx@163.com" );
std::fstream out( "person.pb", std::ios::out | std::ios::binary | std::ios::trunc );
person.SerializeToOstream( &out );
out.close();
// 從文件中讀取數據, 并且反序列化
Test::Person person1;
std::fstream in( "person.pb", std::ios::in | std::ios::binary );
if ( !person1.ParseFromIstream( &in ) ) {
std::cerr << "Failed to parse person.pb." << std::endl;
exit(1);
}
std::cout << "ID: " << person1.id() << std::endl;
std::cout << "name: " << person1.name() << std::endl;
if ( person1.has_email() ) {
std::cout << "e-mail: " << person1.email() << std::endl;
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
getchar();
return 0;
}
輸出:
ID : 123
name : liquidx
e-mail : liquidx@163.com
產生的person.pb內容如下(28字節):
liquidx{liquidx@163.com
試用完畢:
感覺Protocol Buffers挺好用的, 項目的某些xml部分可以使用它來替代,這樣在數據讀取和操作上比xml更加方便直接, 且效率高效!
用它也可以在網絡處理上得到一些好處!