標籤:
1、:https://code.google.com/p/protobuf/downloads/list
安裝 ./configure && make && make install
2、試執行 protoc 命令,如果提示連結庫錯誤,則執行 ldconfig
3、編譯 .proto 檔案成 C++ 標頭檔和源檔案
protoc Login.proto --cpp_out=.
註:可以使用 protoc *.proto --cpp_out=. 批量編譯多個 proto 檔案。
4、上面的 Login.proto 檔案內容如下:
package s3;message Login{ required string username = 1; required string password = 2;}
解析:看到訊息定義中的 1,2 嗎?每個欄位都有唯一的一個標識符,這些標識符是用來在訊息的二進位格式中識別各個欄位的,一旦開始使用就不能夠再改變。其中 1~15 的標識號在編碼的時候會佔用一個位元組,16~2047 的標識號則佔用2個位元組。所以應該為那些頻繁出現的訊息元素保留 1~15 的標識號。
最小的標識號可以從1開始,最大到229 - 1, or 536,870,911。不可以使用其中的[19000-19999]的標識號, Protobuf協議實現中對這些進行了預留。如果非要在.proto檔案中使用這些預留標識號,編譯時間就會警示。
5、編寫測試檔案 test.cpp 如下:
#include "Login.pb.h"#include <iostream>#include <fstream>bool write(){ s3::Login obj; obj.set_username("aaaaaa"); obj.set_password("111111"); std::fstream output("Login.log", std::ios::out | std::ios::trunc | std::ios::binary); if(!obj.SerializeToOstream(&output)) { return false; } return true;}bool read(){ s3::Login obj; std::fstream input("Login.log",std::ios::in | std::ios::binary); if(!obj.ParseFromIstream(&input)) { return false; } std::cout<<"username:"<<obj.username()<<std::endl; std::cout<<"password:"<<obj.password()<<std::endl; return true;}int main(){ if(write()) read();}
上面會輸出: tianya123456
解析:表面上看是12個字元,實際上是12+3=15個字元,以ASCII 10 為開頭字元,然後每個欄位前有一個字元,其ASCII 等於該欄位的長度,所以上面的輸出實際上是:
10 6 97 97 97 97 97 97 97 6 49 49 49 49 49 49
但這是所有欄位都是字串的情況,如果有 int32 的話,就不一樣了,反正注意看到的長度不是真正的長度就好了,pb能夠進行序列化和還原序列化就是依據這個來的。
另外,開發過程中需要經常查看資料,可以調用對象的 DebugString() 函數即可返回可讀性良好的資料。
6、編寫 CMakeLists.txt 如下:
add_executable(test test.cpp Login.pb.cc)target_link_libraries(test protobuf)
或者直接使用:
g++ test.cpp Login.pb.cc -o test -lprotobuf
7、常用方法:
bool SerializeToString(string* output) const: 序列化訊息,將儲存位元組的以string方式輸出。注意位元組是二進位,而非文本;
bool ParseFromString(const string& data): 解析給定的string
bool SerializeToOstream(ostream* output) const: 寫訊息給定的c++ ostream中
bool ParseFromIstream(istream* input): 從給定的c++ istream中解析出訊息
8、參考:
http://hideto.iteye.com/blog/445848
開發人員指南:http://blog.163.com/jiang_tao_2010/blog/static/12112689020114305013458/
protobuf 學習 (轉載)