本文共 2594 字,大约阅读时间需要 8 分钟。
1. 首先了解protobuf是什么?
protobuf是Google提供的一种开源序列化工具。简而言之,是一种编解码的工具。举个例子来说,就是把一些简单的字符串翻译成一些特定的结构,或者二进制文件。
比如 名字:star, ID: 100, 消息:hello, 如果这样一个元组进行序列化翻译成xml,会变成如下
<test> <!--表示根标签-->
<person> <!--表示一组值-->
<name> star </name>
<ID> 100 </ID>
<message> hello </message>
</person>
</test>
经过这样的序列化,很显然的好处是可以结构化的显示,而存储的时候可以使用字符串,或者二进制。而google提供的protobuf则给出了一套库,可以定以一个结构体,由此生成对应的 *.h 和 *.cc, 然后再用它提供的函数可以把结构体转化为二进制,或者把村好的二进制转化为对应的结构体。
2. 下载google的protobuf,并安装
protobuf的下载地址为:
解压后,进入解压目录,然后执行安装命令:
./configure
make check & make install
3. 新建一个目录,作为测试,(名字随便咯)。然后开始测试
3.1 构建一个文件,命名为hello.proto, 内容如下
1 message test
2 { 3 required int32 id = 1; /× required是必填字段 */ 4 required string name = 2; /× 1, 2, 3表示标签,是第几个字段的意思 ×/ 5 optional string message = 3; /*optional是可选字段,即可以有可以没有×/ 6 }/× 在google的文档中,有这样一段话,是说google的一部分工程师认为,optional比required好,因为在编解码时候,不认识的字段也不会产生报错×/
/× 另外还有一种标签叫做 repeated, 这个类似于数组,如何存多个同样的类型时,可以用这样的的标签×/
然后执行命令: protoc hello.proto --cpp_out=./
3.2 构建测试程序 test.cpp, 内容如下
18 #include <iostream>
19 #include <fstream> 20 #include <string> 21 #include "hello.pb.h" 22 23 using namespace std; 24 25 int main() 26 { 27 test mytest; 28 mytest.set_id(100); 29 mytest.set_name("star"); 30 mytest.set_message("hello world!"); 31 32 fstream output("./data.txt", ios::out | ios::trunc | ios::binary ); 33 if( !mytest.SerializeToOstream(&output)) 34 { 35 cerr << "Failed to store data " << endl; 36 return -1; 37 } 38 39 output.close(); 40 41 test mytest1; 42 fstream input("./data.txt", ios::in | ios::binary ); 43 if( !mytest1.ParseFromIstream(&input) ) 44 { 45 cerr << "Failed to parse data " << endl; 46 return -1; 47 } 48 input.close(); 49 50 cout << mytest1.id() << endl; 51 cout << mytest1.name() << endl; 52 cout << mytest1.message() << endl; 53 54 return 0; 55 }
3.3 编译命令:g++ hello.pb.cc test.cpp -lprotobuf
-lprotobuf 表示连接protobuf的库
3.4 运行./a.out看结果
star@ubuntu:~/test/protobuf$ ./a.out
100 star hello world!3.5 查看data.txt
star@ubuntu:~/test/protobuf$ cat data.txt dstar
hello world!star@ubuntu:~/test/protobuf$可以看得出来,已经存储的格式是我们不认识的二进制格式
4. protobuf的小小遗憾
查阅protobuf的文档发现,貌似目前不支持map, vector这种原生的stl结构。
还有其他方面的补充,后续边做边总结上来吧
--------------------------------------------------
如果出了下面的错误,是安装库导致的,做软连接修复
运行,ubuntu下默认报错
protoc: error while loading shared libraries: libprotobuf.so.7: cannot open shared object file: No such file or directory
转载地址:http://tpoji.baihongyu.com/