一、下載地址:https://code.google.com/p/protobuf/downloads/listios
安裝 ./configure && make && make installide
二、試執行 protoc 命令,若是提示連接庫錯誤,則執行 ldconfig函數
三、編譯 .proto 文件成 C++ 頭文件和源文件測試
protoc Login.proto --cpp_out=.
注:可使用 protoc *.proto --cpp_out=. 批量編譯多個 proto 文件。 ui
四、上面的 Login.proto 文件內容以下:google
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文件中使用這些預留標識號,編譯時就會報警。spa
五、編寫測試文件 test.cpp 以下:code
#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() 函數便可返回可讀性良好的數據。
六、編寫 CMakeLists.txt 以下:
add_executable(test test.cpp Login.pb.cc) target_link_libraries(test protobuf)
或者直接使用:
g++ test.cpp Login.pb.cc -o test -lprotobuf
七、經常使用方法:
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中解析出消息
八、參考:
http://hideto.iteye.com/blog/445848
開發者指南:http://blog.163.com/jiang_tao_2010/blog/static/12112689020114305013458/