Protocol Buffer学习教程之类库应用(四)
此教程是通过一个简单的示例,给C++开发者介绍一下如何使用protocol buffers编程,主要包括以下几部分:
定义一个.proto文件
如何使用protocol buffer编译器生成C++类文件
如何使用Protocol buffer api读写消息
这并不是分全面的protocol buffer的C++编程手册,更详尽的资料请参见Protocol Buffer Language Guide(https://developers.google.com/protocol-buffers/docs/proto), the C++ API Reference (https://developers.google.com/protocol-buffers/docs/reference/cpp/index.html), the C++ Generated Code Guide (https://developers.google.com/protocol-buffers/docs/reference/cpp-generated), 和the Encoding Reference (https://developers.google.com/protocol-buffers/docs/encoding)
定义一个.proto文件
创建一个文本文件,重命名为“addressbook.proto”,注意扩展名为“.proto”。
syntax = "proto2";
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 phones = 4;
}
message AddressBook {
repeated Person people = 1;
}
生成类文件
然后通过前面第三部份介绍生成的proto.exe编译器,生成C++类文件,在命令行中,cd到proto.exe根目录,执行以下命令:
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
然后将生成两个文件addressbook.pb.h和addressbook.pb.cc。打开头文件,能看到以下内容:
// 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();
in