假设我有2个Protobuf消息,A和B.它们的总体结构相似,但不完全相同。所以我们把共享的东西放到了一个我们称为Common的单独消息中。这工作很好。在Python中访问未知类型Protobuf消息的字段
但是,我现在面临以下问题:存在一个特殊情况,我必须处理序列化消息,但我不知道它是A型还是B型消息。我有一个工作解决方案在C++中(如下所示),但我没有找到一种方法来在Python中完成同样的事情。
例子:
// file: Common.proto
// contains some kind of shared struct that is used by all messages:
message Common {
...
}
// file: A.proto
import "Common.proto";
message A {
required int32 FormatVersion = 1;
optional bool SomeFlag [default = true] = 2;
optional Common CommonSettings = 3;
... A-specific Fields ...
}
// file: B.proto
import "Common.proto";
message B {
required int32 FormatVersion = 1;
optional bool SomeFlag [default = true] = 2;
optional Common CommonSettings = 3;
... B-specific Fields ...
}
工作液在C++
在C++中我使用反射API来获取这样的访问CommonSettings领域:
namespace gp = google::protobuf;
...
Common* getCommonBlock(gp::Message* paMessage)
{
gp::Message* paMessage = new gp::Message();
gp::FieldDescriptor* paFieldDescriptor = paMessage->GetDescriptor()->FindFieldByNumber(3);
gp::Reflection* paReflection = paMessage->GetReflection();
return dynamic_cast<Common&>(paReflection->GetMessage(*paMessage,paFieldDescriptor));
}
方法'getCommonBlock'我们es FindFieldByNumber()获取我试图获取的字段的描述符。然后它使用反射来获取实际数据。 getCommonBlock只要公共字段保持位于索引3,就可以处理类型A,B或任何未来类型的消息。
我的问题是:有没有办法做类似的事情Python?我一直在寻找Protobuf documentation,但无法想出办法。
这将工作,如果我有一个obj的实例。也许我应该澄清一下我的问题:我以典型的protobuf方式接收消息,作为序列化的blob(二进制内存流)。如何在不知道底层消息类型的情况下实例化obj? – djf