[英]Convert message parsed via `DynamicMessageFactory` to concrete subtype
I'm creating a library that encompasses the parsing of protobuf messages. 我正在创建一个包含protobuf消息解析的库。 As the library cannot know for which messages it will be used, it parses messages using a
google::protobuf::DynamicMessageFactory
. 由于该库无法确定将使用哪些消息,因此它使用
google::protobuf::DynamicMessageFactory
解析消息。
However, I would like to be able to pass the parsed messages back to other parts of the program which know about the actual message types. 但是,我希望能够将解析的消息传递回程序的其他部分,这些部分知道实际的消息类型。
Same question in other words: I have a const google::protobuf Message*
created via google::protobuf::compiler::Importer
and google::protobuf::DynamicMessageFactory
. 换句话说,同样的问题:我有一个通过
google::protobuf::compiler::Importer
和google::protobuf::DynamicMessageFactory
创建的const google::protobuf Message*
。 After parsing, I know for a fact that the message is actually a TestMessage
(and the program knows about the class), can I convert the Message*
into a TestMessage
somehow? 解析之后,我就知道该消息实际上是一个
TestMessage
(并且程序知道该类),我可以将Message*
转换为TestMessage
吗?
I cannot simply dynamic_cast
the message, the result of the cast is always NULL
if the message was parsed with the general Message::ParseFromXXX
which I'm guessing is because those methods just return some kind of proxy objects and cannot know about the actual message classes. 我不能简单地
dynamic_cast
消息,如果消息是用通用的Message::ParseFromXXX
解析的,则转换的结果始终为NULL
,因为我猜这是因为这些方法仅返回某种代理对象,并且不知道实际消息类。
I've also tried the following: 我也尝试了以下方法:
//message is a const google::protobuf::Message* parsed using DynamicMessageFactory
TestMessage *tr = new TestMessage;
tr->CopyFrom( *message );
but that fails with protobuf saying "trying to merge messages of different types". 但这以protobuf说“试图合并不同类型的消息”失败。 Note that
tr->GetTypeName()
and message->GetTypeName()
do return the same type name. 请注意,
tr->GetTypeName()
和message->GetTypeName()
确实返回相同的类型名称。
I'm thankful for any help 我很感谢你的帮助
Does TestMessage actually inherit from Message? TestMessage实际上是否从Message继承? The fact that dynamic_cast returns null suggests that it doesn't, which means that the classes are unrelated, and it doesn't make sense trying to cast from one to the other.
dynamic_cast返回null的事实表明它没有,这意味着这些类是不相关的,并且尝试从一个类转换为另一个类是没有意义的。 Or maybe it uses private inheritance.
或者,它使用私有继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.