This tutorial provides a basic C++ programmer’s introduction to working with protocol buffers. By walking through creating a simple example application, it shows you how to
- Define message formats in a .proto file.
- Use the protocol buffer compiler.
- Use the C++ protocol buffer API to write and read messages.
This isn’t a comprehensive guide to using protocol buffers in C++. For more detailed reference information, see the Protocol Buffer Language Guide, the C++ API Reference, the C++ Generated Code Guide, and the Encoding Reference.
简单的Protocol Buffer例子。
Defining Your Protocol Format
To create your address book application, you’ll need to start with a .proto file. The definitions in a .proto file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message. Here is the .proto file that defines your messages, addressbook.proto.
创建一个后缀名为.proto的文件,下面下一个addressbook.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;
}
As you can see, the syntax is similar to C++ or Java. Let’s go through each part of the file and see what it does.
语法跟C++或Java相似。
The .proto file starts with a package declaration, which helps to prevent naming conflicts between different projects. In C++, your generated classes will be placed in a namespace matching the package name.
首先需要一个package声明,用来防止在不同项目中的命令冲突。在C++中,这个package声明会被翻译成namespace命名空间,然后里面是翻译的你定义的类。
接下来,