Protocol Buffer Basics: C++ 简单的Protocol Buffer C++例子

本文档是C++程序员使用Protocol Buffer的基础教程。通过创建一个简单的示例,介绍了如何在.proto文件中定义消息格式,使用编译器,以及利用C++ API进行消息读写。涉及内容包括消息定义、编译、API接口、枚举和嵌套类、标准消息方法以及序列化和解析。
摘要由CSDN通过智能技术生成

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命名空间,然后里面是翻译的你定义的类。

接下来,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值