【问题标题】:Protobuf: Understanding the compiled output of proto filesProtobuf:了解 proto 文件的编译输出
【发布时间】:2019-02-06 19:36:08
【问题描述】:

**大家好, 我是 protobuf 的新手。我试图了解这里的基础知识。 我在目录/path/to/Directory/ 中创建了示例原型文件Test.proto

syntax = "proto2";

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;
}

并用它编译

 protoc -I=/path/to/Directory/ --cpp_out=/path/to/Directory/ /path/to/Directory/Test.proto

这创建了 2 个文件 Test.pb.hTest.pb.cc。现在我可以看到Person 类中有不同的功能。让我们只取函数(源自Test.proto 文件的required string name = 1; 行)

现在编译器完成了它并提供了这些不同的功能:

bool has_name() const;
void clear_name();
static const int kNameFieldNumber = 1;
const ::std::string& name() const;
void set_name(const ::std::string& value);
void set_name(::std::string&& value);
void set_name(const char* value);
void set_name(const char* value, size_t size);
::std::string* mutable_name();
::std::string* release_name();
void set_allocated_name(::std::string* name);

现在我的问题是:我在哪里可以找到每个函数的描述以及它们的作用?

【问题讨论】:

  • 具体来说我想知道mutable_name()release_name()是做什么的?

标签: c++ protoc protocol-buffers


【解决方案1】:

起点是here(静态代码)和here(生成代码)。后者包括您在“具体”中询问的内容的概述 - 搜索:string* mutable_foo()string* release_foo()(注意它们对于 proto2 和 proto3 是重复的)。

【讨论】:

    【解决方案2】:

    根据 C++ Generated Code 的documentation

    string* mutable_foo():返回指向可变字符串的指针 存储字段值的对象。如果之前未设置该字段 调用,则返回的字符串将为空(不是默认值 价值)。调用此函数后,has_foo() 将返回 truefoo() 将返回写入给定字符串的任何值。

    string* release_foo():释放该字段的所有权并 返回字符串对象的指针。调用此之后,调用者 获取分配的字符串对象的所有权,has_foo() 将 返回 false,foo() 将返回默认值。

    您可以在同一页面中找到其余功能的说明。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2019-12-13
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多