一、下载地址: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/