Protocol Buffer Basics: C++中文翻译(Google Protocol Buffers中文教程)_codelast.com的博客-程序员宝宝

技术标签: c++  Linux  string  methods  google  buffer  parsing  






Protocol Buffer Basics: C++Protocol Buffer基础:C++篇)

注:这是本人的翻译,可能不准确,可能有错误,但是基本上可以理解,希望能对大家有所帮助!(转载请注明出处:本文来自learnhard的博客: &


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.

本教程提供了面向C++程序员的protocol buffers的基本介绍。通过创建一个简单的示例程序,它教你如何:

l  定义.proto文件的消息格式。

l  使用protocol buffer的编译器。

l  使用protoco bufferC++ API来读写消息。


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 buffersC++使用的全面教程。要查看更详细的参考资料,请阅如下文章:Protocol Buffer Language GuideC++ API ReferenceC++ Generated Code Guide以及 Encoding Reference

Why Use Protocol Buffers? 为什么要使用protocol buffers

The example we're going to use is a very simple "address book" application that can read and write people's contact details to and from a file. Each person in the address book has a name, an ID, an email address, and a contact phone number.

How do you serialize and retrieve structured data like this? There are a few ways to solve this problem:

·         The raw in-memory data structures can be sent/saved in binary form. Over time, this is a fragile approach, as the receiving/reading code must be compiled with exactly the same memory layout, endianness, etc. Also, as files accumulate data in the raw format and copies of software that are wired for that format are spread around, it's very hard to extend the format.

·         You can invent an ad-hoc way to encode the data items into a single string – such as encoding 4 ints as "12:3:-23:67". This is a simple and flexible approach, although it does require writing one-off encoding and parsing code, and the parsing imposes a small run-time cost. This works best for encoding very simple data.

·         Serialize the data to XML. This approach can be very attractive since XML is (sort of) human readable and there are binding libraries for lots of languages. This can be a good choice if you want to share data with other applications/projects. However, XML is notoriously space intensive, and encoding/decoding it can impose a huge performance penalty on applications. Also, navigating an XML DOM tree is considerably more complicated than navigating simple fields in a class normally would be.

Protocol buffers are the flexible, efficient, automated solution to solve exactly this problem. With protocol buffers, you write a .proto description of the data structure you wish to store. From that, the protocol buffer compiler creates a class that implements automatic encoding and parsing of the protocol buffer data with an efficient binary format. The generated class provides getters and setters for the fields that make up a protocol buffer and takes care of the details of reading and writing the protocol buffer as a unit. Importantly, the protocol buffer format supports the idea of extending the format over time in such a way that the code can still read data encoded with the old format.


Where to Find the Example Code 在哪可以找到示例代码

The example code is included in the source code package, under the "examples" directory. Download it here.


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.


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;


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.



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.



Next, you have your message definitions. A message is just an aggregate containing a set of typed fields. Many standard simple data types are available as field types, including boolint32floatdouble, and string. You can also add further structure to your messages by using other message types as field types – in the above example the Person message contains PhoneNumber messages, while the AddressBook message contains Person messages. You can even define message types nested inside other messages – as you can see, the PhoneNumber type is defined inside Person. You can also define enum types if you want one of your fields to have one of a predefined list of values – here you want to specify that a phone number can be one of MOBILEHOME, or WORK.



The " = 1", " = 2" markers on each element identify the unique "tag" that field uses in the binary encoding. Tag numbers 1-15 require one less byte to encode than higher numbers, so as an optimization you can decide to use those tags for the commonly used or repeated elements, leaving tags 16 and higher for less-commonly used optional elements. Each element in a repeated field requires re-encoding the tag number, so repeated fields are particularly good candidates for this optimization.

在每一项后面的、类似于“= 1”,“= 2”的标志指出了该字段在二进制编码中使用的唯一“标识(tag)”。标识号1~15编码所需的字节数比更大的标识号使用的字节数要少1个,所以,如果你想寻求优化,可以为经常使用或者重复的项采用1~15的标识(tag),其他经常使用的optional项采用≥16的标识(tag)。在重复的字段中,每一项都要求重编码标识号(tag number),所以重复的字段特别适用于这种优化情况。


Each field must be annotated with one of the following modifiers:

·         required: a value for the field must be provided, otherwise the message will be considered "uninitialized". If libprotobuf is compiled in debug mode, serializing an uninitialized message will cause an assertion failure. In optimized builds, the check is skipped and the message will be written anyway. However, parsing an uninitialized message will always fail (by returning false from the parse method). Other than this, a required field behaves exactly like an optional field.

·         optional: the field may or may not be set. If an optional field value isn't set, a default value is used. For simple types, you can specify your own default value, as we've done for the phone number type in the example. Otherwise, a system default is used: zero for numeric types, the empty string for strings, false for bools. For embedded messages, the default value is always the "default instance" or "prototype" of the message, which has none of its fields set. Calling the accessor to get the value of an optional (or required) field which has not been explicitly set always returns that field's default value.

·         repeated: the field may be repeated any number of times (including zero). The order of the repeated values will be preserved in the protocol buffer. Think of repeated fields as dynamically sized arrays.


l  required:必须提供字段值,否则对应的消息就会被认为是“未初始化的”。如果libprotobuf是以debug模式编译的,序列化一个未初始化的消息(message)将会导致一个断言错误。在优化过的编译情况下(译者注:例如release),该检查会被跳过,消息会被写入。然而,解析一个未初始化的消息仍然会失败(解析函数会返回false)。除此之外,一个required的字段与一个optional的字段就没有区别了。

l  optional:字段值指定与否都可以。如果没有指定一个optional的字段值,它就会使用默认值。对简单类型来说,你可以指定你自己的默认值,就像我们在上面的例子中对phone numbertype字段所做的一样。如果你不指定默认值,就会使用系统默认值:数据类型的默认值为0string的默认值为空字符串,bool的默认值为false。对嵌套消息(message)来说,其默认值总是消息的“默认实例”或“原型”,即:没有任何一个字段是指定了值的。调用访问类来取一个未显式指定其值的optional(或者required)的字段的值,总是会返回字段的默认值。

l  repeated:字段会重复N次(N可以为0)。重复的值的顺序将被保存在protocol buffer中。你只要将重复的字段视为动态大小的数组就可以了。

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use onlyoptional and repeated. However, this view is not universal.



You'll find a complete guide to writing .proto files – including all the possible field types – in the Protocol Buffer Language Guide. Don't go looking for facilities similar to class inheritance, though – protocol buffers don't do that.

你可以在Protocol Buffer Language Guide一文中找到编写.proto文件的完整指南(包括所有可能的字段类型)。但是,不要想在里面找到与类继承相似的特性,因为protocol buffers不是拿来做这个的。

Compiling Your Protocol Buffers 编译你的protocol buffers

Now that you have a .proto, the next thing you need to do is generate the classes you'll need to read and write AddressBook (and hence Personand PhoneNumber) messages. To do this, you need to run the protocol buffer compiler protoc on your .proto:

1.    If you haven't installed the compiler, download the package and follow the instructions in the README.

2.    Now run the compiler, specifying the source directory (where your application's source code lives – the current directory is used if you don't provide a value), the destination directory (where you want the generated code to go; often the same as $SRC_DIR), and the path to your.proto. In this case, you...:

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

Because you want C++ classes, you use the --cpp_out option – similar options are provided for other supported languages.

This generates the following files in your specified destination directory:

·         addressbook.pb.h, the header which declares your generated classes.

·, which contains the implementation of your classes.

在得到了一个.proto文件之后,下一步你就要生成可以读写AddressBook消息(当然也就包括了Person以及PhoneNumber消息)的类了。此时你需要运行protocol buffer编译器来编译你的.proto文件:

1. 如果你还没有安装该编译器,下载安装包 并参照README文件中的说明来安装

2. 安装了之后,就可以运行编译器了。指定源目录(即你的应用程序源代码所在的目录——如果不指定的话,就使用当前目录)、目标目录(即生成的代码放置的目录,通常与$SRC_DIR是一样的),以及你的.proto文件所在的目录。在我们这里,可以这样用:

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

因为需要生成的是C++类,所以使用了--cpp_out选项参数——protocol buffers也为其他支持的语言提供了类似的选项参数。这样就可以在你指定的目标目录下生成如下文件:

l  addressbook.pb.h声明你生成的类的头文件。

l  addressbook.pb.cc你生成的类的实现文件。


The Protocol Buffer API

Let's look at some of the generated code and see what classes and functions the compiler has created for you. If you look in tutorial.pb.h, you can see that you have a class for each message you specified in tutorial.proto. Looking closer at the Person class, you can see that the complier has generated accessors for each field. For example, for the nameidemail, and phone fields, you have these methods:

让我们看一下生成的代码,了解一下编译器为你创建了什么样的类和函数。如果你看了tutorial.pb.h文件,就会发现你得到了一个类,它对应于tutorial.proto文件中写的每一个消息(message)。更深入一步,看看Person 类:编译器为每一个字段生成了读写函数。例如,对nameidemail以及phone字段,分别有如下函数:

  // 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;
  inline ::tutorial::Person_PhoneNumber* mutable_phone(int index);
  inline ::tutorial::Person_PhoneNumber* add_phone();

As you can see, the getters have exactly the name as the field in lowercase, and the setter methods begin with set_. There are also has_ methods for each singular (required or optional) field which return true if that field has been set. Finally, each field has a clear_ method that un-sets the field back to its empty state.

正如你所看到的,getter函数具有与字段名一模一样的名字,并且是小写的,而setter函数都是以set_前缀开头。此外,还有has_前缀的函数,对每一个单一的(requiredoptional的)字段(译者注:此处估计是“非repeated字段”的意思)来说,如果字段被置(set)了值,该函数会返回true。最后,每一个字段还有一个clear_前缀的函数,用来将字段重置(un-set)到空状态(empty state)。


While the numeric id field just has the basic accessor set described above, the name and email fields have a couple of extra methods because they're strings – a mutable_ getter that lets you get a direct pointer to the string, and an extra setter. Note that you can call mutable_email() even ifemail is not already set; it will be initialized to an empty string automatically. If you had a singular message field in this example, it would also have a mutable_ method but not a set_ method.

然而,数值类型的字段id就只有如上所述的基本读写函数,nameemail字段则有一些额外的函数,因为它们是string——前缀为mutable_的函数返回string的直接指针(direct pointer)。除此之外,还有一个额外的setter函数。注意:你甚至可以在email还没有被置(set)值的时候就调用mutable_email(),它会被自动初始化为一个空字符串。在此例中,如果有一个单一消息字段,那么它也会有一个mutable_ 前缀的函数,但是没有一个set_ 前缀的函数。


Repeated fields also have some special methods – if you look at the methods for the repeated phone field, you'll see that you can

·         check the repeated field's _size (in other words, how many phone numbers are associated with this Person).

·         get a specified phone number using its index.

·         update an existing phone number at the specified index.

·         add another phone number to the message which you can then edit (repeated scalar types have an add_ that just lets you pass in the new value).

重复的字段也有一些特殊的函数——如果你看一下重复字段phone 的那些函数,就会发现你可以:

l  得到重复字段的_size(换句话说,这个Person关联了多少个电话号码)。

l  通过索引(index)来获取一个指定的电话号码。

l  通过指定的索引(index)来更新一个已经存在的电话号码。

l  向消息(message)中添加另一个电话号码,然后你可以编辑它(重复的标量类型有一个add_前缀的函数,允许你传新值进去)。


For more information on exactly what members the protocol compiler generates for any particular field definition, see the C++ generated code reference.

关于编译器如何生成特殊字段的更多信息,请查看文章C++ generated code reference

Enums and Nested Classes 枚举和嵌套类

The generated code includes a PhoneType enum that corresponds to your .proto enum. You can refer to this type as Person::PhoneType and its values as Person::MOBILEPerson::HOME, and Person::WORK (the implementation details are a little more complicated, but you don't need to understand them to use the enum).

生成的代码中包含了一个PhoneType 枚举,它对应于.proto文件中的那个枚举。你可以把这个类型当作Person::PhoneType,其值为Person::MOBILEPerson::HOMEPerson::WORK(实现的细节稍微复杂了点,但是没关系,不理解它也不会影响你使用该枚举)。


The compiler has also generated a nested class for you called Person::PhoneNumber. If you look at the code, you can see that the "real" class is actually called Person_PhoneNumber, but a typedef defined inside Person allows you to treat it as if it were a nested class. The only case where this makes a difference is if you want to forward-declare the class in another file – you cannot forward-declare nested types in C++, but you can forward-declare Person_PhoneNumber.

编译器还生成了一个名为Person::PhoneNumber的嵌套类。如果你看看代码,就会发现“真实的”类实际上是叫做Person_PhoneNumber,只不过Person 内部的一个typedef允许你像一个嵌套类一样来对待它。这一点所造成的唯一一个区别就是:如果你想在另一个文件中对类进行前向声明(forward-declare)的话,你就不能在C++中对嵌套类型进行前向声明了,但是你可以对Person_PhoneNumber进行前向声明。

Standard Message Methods 标准消息函数

Each message class also contains a number of other methods that let you check or manipulate the entire message, including:

·         bool IsInitialized() const;: checks if all the required fields have been set.

·         string DebugString() const;: returns a human-readable representation of the message, particularly useful for debugging.

·         void CopyFrom(const Person& from);: overwrites the message with the given message's values.

·         void Clear();: clears all the elements back to the empty state.

These and the I/O methods described in the following section implement the Message interface shared by all C++ protocol buffer classes. For more info, see the complete API documentation for Message.


l  bool IsInitialized() const;:检查是否全部的required字段都被置(set)了值。

l  string DebugString() const;:返回一个易读的消息表示形式,对调试特别有用。

l  void CopyFrom(const Person& from);:用外部消息的值,覆写调用者消息内部的值。

l  void Clear();:将所有项复位到空状态(empty state)。

这些函数以及后面章节将要提到的I/O函数实现了Message 的接口,它们被所有C++ protocol buffer类共享。更多信息,请查看文章 complete API documentation for Message


Parsing and Serialization 解析&序列化

Finally, each protocol buffer class has methods for writing and reading messages of your chosen type using the protocol buffer binary format. These include:

·         bool SerializeToString(string* output) const;: serializes the message and stores the bytes in the given string. Note that the bytes are binary, not text; we only use the string class as a convenient container.

·         bool ParseFromString(const string& data);: parses a message from the given string.

·         bool SerializeToOstream(ostream* output) const;: writes the message to the given C++ ostream.

·         bool ParseFromIstream(istream* input);: parses a message from the given C++ istream.

These are just a couple of the options provided for parsing and serialization. Again, see the Message API reference for a complete list.

最后,每一个protocol buffer类都有读写你所选择的消息类型的函数。它们包括:

l  bool SerializeToString(string* output) const;将消息序列化并储存在指定的string中。注意里面的内容是二进制的,而不是文本;我们只是使用string作为一个很方便的容器。

l  bool ParseFromString(const string& data);从给定的string解析消息。

l  bool SerializeToOstream(ostream* output) const;将消息写入到给定的C++ ostream中。

l  bool ParseFromIstream(istream* input);从给定的C++ istream解析消息。




Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they don't make good first class citizens in an object model. If you want to add richer behaviour to a generated class, the best way to do this is to wrap the generated protocol buffer class in an application-specific class. Wrapping protocol buffers is also a good idea if you don't have control over the design of the .proto file (if, say, you're reusing one from another project). In that case, you can use the wrapper class to craft an interface better suited to the unique environment of your application: hiding some data and methods, exposing convenience functions, etc. You should never add behaviour to the generated classes by inheriting from them. This will break internal mechanisms and is not good object-oriented practice anyway.

protocol buffers和面向对象的设计 protocol buffer类通常只是纯粹的数据存储器(就像C++中的结构体一样);它们在对象模型中并不是一等公民。如果你想向生成的类中添加更丰富的行为,最好的方法就是在应用程序中对它进行封装。如果你无权控制.proto文件的设计的话,封装protocol buffers也是一个好主意(例如,你从另一个项目中重用一个.proto文件)。在那种情况下,你可以用封装类来设计接口,以更好地适应你的应用程序的特定环境:隐藏一些数据和方法,暴露一些便于使用的函数,等等。但是你绝对不要通过继承生成的类来添加行为。这样做的话,会破坏其内部机制,并且不是一个好的面向对象的实践。





这些函数只是用于解析和序列化的几个函数罢了。请再次参考Message API reference以查看完整的函数列表。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。


spring boot+atomikos+mybatis+druid分布式事务实现_一大三千的博客-程序员宝宝_druid 和 jta

配置数据源新建配置类DataSourceConfig:public class DataSourceConfig { private static final String PRIMARY_MAPPER_BASE_PACKAGE = &quot;io.github.yidasanqian.mapper.master&quot;; private static final String BUSINESS_M


既然涉及梯度,不得不先谈谈requires_grad。import torch下面先来做做题:a=torch.tensor([1.1])print(a.requires_grad)#答案是?a=torch.tensor([1.1],requires_grad=True)b=a*2print(b.requires_grad)#答案是?a=torch.tensor([1.1],requires_grad=True)with torch.no_grad(): b=a*2pri_1671465600


SharePoint 2013 的Odata service的常用URI实例:URI实例 解释 _api/web/title 返回web title  _api/web/lists(guid'&amp;lt;list id&amp;gt;') 返回列表 _api/web/lists/getByTitle('Announcements')/fields 返回列表的所有字段 ...

信息系统项目管理师真题2017下半年附答案解析(2)_ME 妖的博客-程序员宝宝

16、针对信息系统,安全可以划分为四个层次,其中不包括()。  A.设备安全 B.人员安全  C.内容安全 D.行为安全【答案】B 【解析】本考题考查的知识点为信息安全基础知识,出自《信息系统项目管理工程师教程(第 3版)》第 1 章 信息化和信息系统,全书第 68、69 页。  安全可言划分以下四个层次:设备安全、数据安全、内容安全、行为安全。  17、以下...

LeetCode 力扣 51. N皇后_wind_liang的博客-程序员宝宝_l皇后力扣

题目描述(困难难度)经典的 N 皇后问题。意思就是摆皇后的位置,每行每列以及对角线只能出现 1 个皇后。输出所有的情况。解法一 回溯法比较经典的回溯问题了,我们需要做的就是先在第一行放一个皇后,然后进入回溯,放下一行皇后的位置,一直走下去,如果已经放的皇后的数目等于 n 了,就加到最后的结果中。然后再回到上一行,变化皇后的位置,然后去找其他的解。期间如果遇到当前行所有的位置都不能放皇后了...




python使用python-docx自动化操作word_Hushi1706IT的博客-程序员宝宝_docx python



使用user_的表select a.constraint_name, a.column_name from user_cons_columns a, user_constraints bwhere a.constraint_name = b.constraint_name and a.constraint_type = 'P' and b.table_name = 'tablename'; 但是可能会存在表格为空所以使用下列all_table使用all_的表select a.cons


前言我们都知道,wireshark可以实现本地抓包,同时Wireshark也支持remote packet capture protocol(rpcapd)协议远程抓包,只要在远程主机上安装相应的rpcapd服务例程就可以实现在本地电脑执行wireshark 捕获远程电脑的流量了。但是各种协议的流量非常巨大,如果我们捕获所有协议的流量,那么数小时内,捕获到的流量将到达几百M,甚至几G。硬盘空间很快就被填满了。所以很有必要,只捕获特定的流量或者不捕获某些流量而捕获其他所有的流量。捕捉过滤器语法语法:&l




【题目描述】给定被除数和除数,求整数商及余数。此题中请使用默认的整除和取余运算,无需对结果进行任何特殊处理。【输入】一行,包含两个整数,依次为被除数和除数(除数非零),中间用一个空格隔开。【输出】一行,包含两个整数,依次为整数商和余数,中间用一个空格隔开。【输入样例】10 3【输出样例】3 1【参考程序】#include&lt;cstdio&gt;using namespa...

9th NENU ACM-ICPC Contest Solving Report_light_starlight的博客-程序员宝宝

第九届东北师范大学ACM-ICPC校赛于2015年4月12日圆满落幕,五个小时赛程共十道题,现公布题解如下:--------------------------------------------------------------------------------------绪→感谢出题组、验题组、翻译组的倾力奉献,人员如下:    Ok_again