访问协议缓冲区扩展字段
Access protocol buffers extension fields
我正在使用 C++ 中的协议缓冲区。我的消息只有一个扩展范围。我想在不知道他们的名字的情况下访问所有的扩展字段,只使用他们的号码。我该怎么做?
message Base {
optional int32 id = 1;
extensions 1000 to 1999;
}
extend Base{
optional int32 id2 = 1000;
}
至此,我已经获得了ExtensionRange
const google::protobuf::Descriptor::ExtensionRange* rng = desc->extension_range(0);
std::cerr << "rng " << rng->start << " " << rng->end << std::endl;
但我不知道要获取 Fielddescriptor*
的扩展名。
有一件奇怪的事情,那就是 extension_count()
返回 0。虽然我在我的 .proto 文件中使用了扩展名。同样,FindExtensionBy[Name/number] 没有按预期工作?
我找到了一个使用反射的解决方案。
const Reflection* ref = message_.GetReflection();
const FieldDescriptor* cfield = ref->FindKnownExtensionByNumber(33);
std::cerr << "cfield->name() " << cfield->name() << std::endl;
现在我现有的解决方案是循环查找分机范围内的所有号码,并获取分机所需的字段描述符。
我还在等待任何 better/different 解决方案,你们。
引用官方descriptor.h
文档:
To get a FieldDescriptor for an extension, do one of the following:
- Get the Descriptor or FileDescriptor for its containing scope, then
call Descriptor::FindExtensionByName() or
FileDescriptor::FindExtensionByName().
- Given a DescriptorPool, call
DescriptorPool::FindExtensionByNumber().
- Given a Reflection for a
message object, call Reflection::FindKnownExtensionByName() or
Reflection::FindKnownExtensionByNumber(). Use DescriptorPool to
construct your own descriptors.
extension_count()
返回 0 的原因是它告诉您嵌套扩展 声明的数量 (对于其他消息类型)。
我正在使用 C++ 中的协议缓冲区。我的消息只有一个扩展范围。我想在不知道他们的名字的情况下访问所有的扩展字段,只使用他们的号码。我该怎么做?
message Base {
optional int32 id = 1;
extensions 1000 to 1999;
}
extend Base{
optional int32 id2 = 1000;
}
至此,我已经获得了ExtensionRange
const google::protobuf::Descriptor::ExtensionRange* rng = desc->extension_range(0);
std::cerr << "rng " << rng->start << " " << rng->end << std::endl;
但我不知道要获取 Fielddescriptor*
的扩展名。
有一件奇怪的事情,那就是 extension_count()
返回 0。虽然我在我的 .proto 文件中使用了扩展名。同样,FindExtensionBy[Name/number] 没有按预期工作?
我找到了一个使用反射的解决方案。
const Reflection* ref = message_.GetReflection();
const FieldDescriptor* cfield = ref->FindKnownExtensionByNumber(33);
std::cerr << "cfield->name() " << cfield->name() << std::endl;
现在我现有的解决方案是循环查找分机范围内的所有号码,并获取分机所需的字段描述符。
我还在等待任何 better/different 解决方案,你们。
引用官方descriptor.h
文档:
To get a FieldDescriptor for an extension, do one of the following:
- Get the Descriptor or FileDescriptor for its containing scope, then call Descriptor::FindExtensionByName() or FileDescriptor::FindExtensionByName().
- Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber().
- Given a Reflection for a message object, call Reflection::FindKnownExtensionByName() or Reflection::FindKnownExtensionByNumber(). Use DescriptorPool to construct your own descriptors.
extension_count()
返回 0 的原因是它告诉您嵌套扩展 声明的数量 (对于其他消息类型)。