【问题标题】:C++ google protobuf: How to create MutableExtension from extension's FieldDescriptorC++ google protobuf:如何从扩展的 FieldDescriptor 创建 MutableExtension
【发布时间】:2019-04-23 02:29:19
【问题描述】:

我有一个包含扩展的消息的原型

message MsgA
{
    extensions 10 to 50;
}

我有另一个具有扩展的原型(仅显示下面的扩展之一)

extend MsgA
{
    optional MsgB msgB = 10;
}
message MsgB
{
    required int32 value = 1;
}

通过 protobuf 代码,我可以获取 MsgB 的描述符和 FileDescriptor,并且可以从那里检索 FieldDescriptor 类型的扩展名“msgB”。我正在通过 protobuf 代码找到扩展,而不是使用从 MsgB proto 生成的代码,因为我试图遍历所有扩展消息,而不是将它们中的每一个硬编码到 MutableExtension 中。 (我理解 MutableExtension(MsgB::msgB) 的硬编码方式,但想使用检索到的扩展名)

我想用 msgB 扩展填充 MsgA 的可变扩展,但 MutableExtension 接受一种

(const ::google::protobuf::internal::ExtensionIdentifier& id) 或

(const ::google::protobuf::internal::ExtensionIdentifier& id, int index)

如何使用找到的 msgB 扩展填充/创建 MutableExtension,或者如何创建 msgB 的 ExtensionIdentifer 以用作创建 MsgA 的 MutableExtension 的输入?

【问题讨论】:

    标签: c++ proto protocol-buffers


    【解决方案1】:

    我想我找到了一种通过反射将扩展扩展到 MsgA 的方法。

    在 MsgA 对象上,检索反射对象。然后在反射对象上使用 MsgA 对象和扩展 FieldDescriptor 对象调用 MutableMessage(FileDescriptor 对象来自定义扩展名的 GetDescriptor()->file(),在这种情况下为 MsgB)。

    MsgA* msgObj;
    FieldDescriptor* ext = fileDescriptor->extension(indexOfExtension);
    auto reflection = msgObj->GetReflection();
    reflection->MutableMessage(msgObj, ext);
    

    这将使用扩展消息填充 MsgA 对象,您可以按索引遍历每个扩展,以使用每个扩展消息填充 MsgA 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多