1. 概述
protobuf(Protocol Buffers )是一種輕便高效的結構化數據存儲格式,可以用於結構化數據串行化,或者說序列化。它很適合做數據存儲或 RPC 數據交換格式。可用於通訊協議、數據存儲等領域的語言無關、平臺無關、可擴展的序列化結構數據格式。目前提供了 C++、Java、Python 三種語言的 API。
特點:
- 結構數據串行化,靈活、高效、自動。
- 相對XML,更小、更快、更簡單。
- 自定義數據結構。
- 動態更新數據結構。
2. 安裝protobuf
首先,可以從github protobuf工程獲取最新版本的源碼。然後安裝上面的README教程進行安裝。大致過程如下:
(1). 運行autogen.sh,生產configure腳本。此過程會自動下載gmock文件,運行autorun、autoconf等。
(2). 編譯安裝protobuf。
$ ./configure
$ make
$ make check
$sudo make install
默認情況下,程序會安裝到/usr/local/
目錄,但是有些平臺上/usr/local/lib
並不在LD_LIBRARY_PATH
的環境變量中。我們可以通過以下語句配置程序的安裝目錄。
./configure –prefix=/usr
3. 使用protobuf
3.1 編寫接口文件(.proto)
.proto文件類似於c/c++中的數據定義,這裏以test.proto
爲例:
message TestMsg
{
required int32 id=1;
required string describe=2;
optional string opt=3;
}
上面定義了一個消息,有三個成員,必須有的int類型的id,string類型的describe和可選的string類型的opt。最上面也可以加上包名package pkg_name
。
3.2 編譯.proto文件
用 Protobuf 編譯器將該文件編譯成目標語言,這裏使用c++。
protoc -I=$SRC_DIR –cpp_out=$DST_DIR $SRC_DIR/test.proto
$SRC_DIR是目標路徑,–cpp_out輸出c++語言版本文件。這裏會生成兩個文件test.pb.h和test.pb.cc。生產的頭文件中定義了一個TestMsg的類,後面會有對它的一系列序列化操作。
3.3 編寫運行測試程序
爲了方便測試,這裏只寫一個小程序write.c
,講message序列化爲string類型的字符串,然後再反序列化回來。測試程序如下:
#include "test.pb.h"
#include < stdio.h>
#include < string>
int main()
{
TestMsg tmsg;
tmsg.set_id(1001);
tmsg.set_describe("this is a describe.");
std::string s;
tmsg.SerializeToString(&s);
printf("%s\n",s.c_str());
TestMsg msg2;
msg2.ParseFromString(s);
printf("id:%d\t describe:%s\n",msg2.id(), msg2.describe().c_str());
return 0;
}
編譯和運行程序。
c++ -o write write.cc test.pb.cc
pkg-config --cflags --libs protobuf
運行結果:
this is a describe.
id:1001 describe:this is a describe.