protobuf入门指南
1, 下载compiler和源代码,或直接下bin包
http://code.google.com/p/protobuf/downloads/
build protobuf:
- ./configure
- make
- make check
- make install
2, 创建一个addressbook.proto
- 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;
- }
3, 生成C++的stub
- protoc --cpp_out=. ./addressbook.proto
运行上面的命令将生成addressbook.pb.h和addressbook.pb.cc
4, 成员访问代码
部分.h代码及注释:
// 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(); //如为空,则new a buffer并返回之。 // 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; //repeated 字段的数量 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; //访问第index个字段 inline ::tutorial::Person_PhoneNumber* mutable_phone(int index); inline ::tutorial::Person_PhoneNumber* add_phone();
5, 用法
就不说了吧,见上方.h代码段及注释,比什么例子要清楚多了。