C++ google protobuf:如何从扩展的 FieldDescriptor 创建 MutableExtension

C++ google protobuf: How to create MutableExtension from extension's FieldDescriptor

我有一个原型,其中有一条包含扩展的消息

message MsgA
{
    extensions 10 to 50;
}

我有另一个带有扩展的原型(下面只显示了其中一个扩展)

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

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

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

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

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

如何 populate/create MutableExtension 与找到的 msgB 扩展名或如何创建 msgB 的 ExtensionIdentifer 以用作创建 MsgA 的 MutableExtension 的输入?

我想我找到了一种通过反射将扩展名放入 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 对象。