ProtoBuffer 简单例子

最近学了一下protobuf,写了一个简单的例子,如下:

person.proto文件

[cpp] view plain copy
 
  1. message Person{  
  2.     required string name = 1;  
  3.     required int32 age = 2;  
  4.     optional string email = 3;  
  5.     enum PhoneType{   
  6.         MOBILE = 1;  
  7.         HOME = 2;  
  8.         WORK = 3;  
  9.     }  
  10.     message Phone{  
  11.         required int32 id = 1;  
  12.         optional PhoneType type = 2 [default = HOME];  
  13.     }  
  14.     repeated string phoneNum = 4;  //对应于cpp的vector  
  15. }  
安装好protoc以后,执行protoc person.proto --cpp_out=. 生成 person.pb.h和person.pb.cpp

写文件(write_person.cpp):

[cpp] view plain copy
 
  1. #include <iostream>  
  2. #include "person.pb.h"  
  3. #include <fstream>  
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. int main(){  
  9.     string buffer;  
  10.     Person person;  
  11.     person.set_name("chemical");  
  12.     person.set_age(29);  
  13.     person.set_email("ygliang2009@gmail.com");  
  14.     person.add_phonenum("abc");  
  15.     person.add_phonenum("def");  
  16.     fstream output("myfile",ios::out|ios::binary);  
  17.     person.SerializeToString(&buffer); //用这个方法,通常不用SerializeToOstream  
  18.     output.write(buffer.c_str(),buffer.size());  
  19.     return 0;  
  20. }  
编译时要把生成的cpp和源文件一起编译,如下:g++ write_person.cpp person.pb.cpp -o write_person -I your_proto_include_path -L your_proto_lib_path -lprotoc -lprotobuf运行时记得要加上LD_LIBRARY_PATH=your_proto_lib_path

读文件(read_person.cpp):

[cpp] view plain copy
 
  1. #include <iostream>  
  2. #include "person.pb.h"  
  3. #include <fstream>  
  4. #include <string>  
  5.   
  6. using namespace std;  
  7.   
  8. int main(){  
  9.     Person *person = new Person;  
  10.     char buffer[BUFSIZ];  
  11.     fstream input("myfile",ios::in|ios::binary);  
  12.     input.read(buffer,sizeof(Person));  
  13.     person->ParseFromString(buffer);  //用这个方法,通常不用ParseFromString  
  14.     cout << person->name() << person->phonenum(0) << endl;  
  15.     return 0;  
  16. }  
编译运行方法同上:g++ read_person.cpp person.pb.cpp -o read_person -I your_proto_include_path -L your_proto_lib_path -lprotoc -lprotobuf
 
原文地址:https://www.cnblogs.com/mfryf/p/5263013.html