且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

protobuf c++入门

更新时间:2022-09-18 16:54:21

1、在.proto文件中定义消息格式

2、使用protobuf编译器
3、使用c++ api来读写消息
 
0、为何使用protobuf?
 
1、原始内存数据结构,可以以二进制方式sent/saved.这种方式需要相同的内存布局和字节序。
2、以ad-hoc方式将数据项编码成一个简单字符串----比如,将4个int类型编码成"12:3:-23:67"。这种方式简灵活。适用于简单数据。
3、将数据序列化为XML。这种方式很流行,因为xml可读性好,编码解码方便,性能也好。仅仅XML dom树比较复杂。
 
protobuf可以很好的解决上述问题。你编写一个.proto文件来描述数据结构。protobuf编译器使用它创建一个类,使用二进制方式自动编码/解码该数据结构。生成的类提供getter/setter方法。
 
最重要的是,protobuf支持在此基础上进行格式扩展。
 
示例
 
1、定义协议格式
 

package tutorial; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } message AddressBook { repeated Person person = 1; }

 
该结构与c++或java很像.
 
.proto文件以包声明开始,防止名字冲突。
简单类型:bool, int32, float, double, string.
其它类型:如上述的Person, PhoneNumber
 
类型可以嵌套。
“=1”, “=2”标识唯一“tag”.tag数1-15需要至少一个字节。
 
required: 必须设置它的值
optional: 可以设置,也可以不设置它的值
repeated: 可以认为是动态分配的数组
google工程师认为使用required威害更大, 他们更喜欢使用optional, repeated.
 
 
2、编译你的协议
 
运行protoc 来生成c++文件:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
生成的文件为:
addressbook.pb.h, 
addressbook.pb.cc
 
3、protobuf API
 
生成的文件中有如下方法:
// name
  inline bool has_name() const;
  inline void clear_name();
  inline const ::std::string& name() const;
  inline void set_name(const ::std::string& value);
  inline void set_name(const char* value);
  inline ::std::string* mutable_name();

  // id
  inline bool has_id() const;
  inline void clear_id();
  inline int32_t id() const;
  inline void set_id(int32_t value);

  // email
  inline bool has_email() const;
  inline void clear_email();
  inline const ::std::string& email() const;
  inline void set_email(const ::std::string& value);
  inline void set_email(const char* value);
  inline ::std::string* mutable_email();

  // phone
  inline int phone_size() const;
  inline void clear_phone();
  inline const ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >& phone() const;
  inline ::google::protobuf::RepeatedPtrField< ::tutorial::Person_PhoneNumber >* mutable_phone();
  inline const ::tutorial::Person_PhoneNumber& phone(int index) const