Are you sure that "message" is a MsgFrame class? Since dynamic_cast<>() is 
failing, I suspect it is not.

You should be aware that m1->CopyFrom(m2) can succeed even if m1 and m2 
have different C++ classes, as long as both classes have the same 
descriptor. For example, m1 could be MsgFrame and m2 could be 
DynamicMessage, and CopyFrom() will succeed. But for C++ dynamic_cast<>() 
they must be the exact same class.

If you are using DynamicMessageFactory, you can probably solve this problem 
by calling:

  DynamicMessageFactory factory;

This will make DynamicMessageFactory return instances of compiled-in 
classes where possible, instead of DynamicMessage.


On Wednesday, February 17, 2016 at 11:09:08 AM UTC-8, Elmar van wrote:
> Hello,
> I'm trying to have an abstract layer which delivers 
> google::protobuf::Message, I assign a type by setting the descriptor.
> This all works great.
> Now I have a general callback function which has one argument, a reference 
> to a protobuf message.
> static void receiveCallback(google::protobuf::Message &message)
> Now another software layer of mine uses this abstract library, this layer 
> has messages defined. So I'm looking for a performant way to cast this 
> reference and I'm not quite sure why it wont work.
> Using a dynamic_cast throws a bad cast exception, using a static_cast the 
> datas are not set.
> try {
>    MsgFrame & frame = dynamic_cast<MsgFrame&>(message);
>    LOG(DEBUG)<<frame.number();
> } catch (const std::bad_cast& e) {
>    LOG(WARNING) << e.what();
> }
> However when I create a new MsgFrame and use CopyFrom(..) it works as 
> expected. But this is not wanted due to performance overhead.
> What is the correct way to cast it?
> Thanks in advance!

You received this message because you are subscribed to the Google Groups 
"Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
To post to this group, send email to
Visit this group at
For more options, visit

Reply via email to