首页 > 其他 > 详细

protobuf入门指南

时间:2014-01-16 00:19:22      阅读:453      评论:0      收藏:0      [点我收藏+]

1, 下载compiler和源代码,或直接下bin包
http://code.google.com/p/protobuf/downloads/ 

build protobuf: 

C++代码  bubuko.com,布布扣
  1. ./configure  
  2. make  
  3. make check  
  4. make install  



2, 创建一个addressbook.proto 

C++代码  bubuko.com,布布扣
  1. package tutorial;  
  2.   
  3. message Person {  
  4.   required string name = 1;  
  5.   required int32 id = 2;  
  6.   optional string email = 3;  
  7.     
  8.   enum PhoneType {  
  9.     MOBILE = 0;  
  10.     HOME = 1;  
  11.     WORK = 2;  
  12.   }  
  13.     
  14.   message PhoneNumber {  
  15.     required string number = 1;  
  16.     optional PhoneType type = 2 [default = HOME];  
  17.   }  
  18.     
  19.   repeated PhoneNumber phone = 4;   
  20. }  
  21.   
  22. message AddressBook {  
  23.   repeated Person person = 1;  
  24. }  



3, 生成C++的stub 

C++代码  bubuko.com,布布扣
  1. protoc --cpp_out=. ./addressbook.proto  


运行上面的命令将生成addressbook.pb.h和addressbook.pb.cc 

 

4, 成员访问代码

部分.h代码及注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 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代码段及注释,比什么例子要清楚多了。

 

protobuf入门指南

原文:http://www.cnblogs.com/wishing/p/3517140.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!