oneof feature example using c++

55 views
Skip to first unread message

SIMON BABY

unread,
Aug 9, 2019, 5:10:26 PM8/9/19
to Protocol Buffers
Hello,

I am new to protobuf. I read the document and came to know that the oneof field is similar to union in c or c++. I have the below messages to send and receive. Can come one please send me the sending side and receiving side parser to get the particular message type and process it.
 

essage Message1 {
   string a = 1;
   string b = 2;
}

message Message2 {
   int64 id = 1;
   string data = 2;
}




message WrapperMessage {
   oneof msg {
        Message1 m1 = 2;
        Message2 m2 = 3;
    }   
}


rgds
Simon
Message has been deleted
Message has been deleted
Message has been deleted

Matthew Allen

unread,
Aug 12, 2019, 11:11:07 PM8/12/19
to Protocol Buffers
Here is some example code you could play with:

#include "test.pb.h"

int main(int args, const char **arg)
{
    Message1 m1;
    m1.set_a("22");
    m1.set_b("33");
    WrapperMessage wm1;
    wm1.set_allocated_m1(&m1);
    auto s = wm1.SerializeAsString();

    WrapperMessage wm2;
    wm2.ParseFromString(s);
    if (wm2.has_m1())
    {
        auto msg1 = wm2.m1();
        auto msg1a = msg1.a();
        auto msg1b = msg1.b();
    }

    return 0;
}

Adam Cozzette

unread,
Aug 15, 2019, 6:06:17 PM8/15/19
to Matthew Allen, Protocol Buffers
Matthew, I suspect you have a version mismatch between your protoc and libprotobuf. For C++ the libprotobuf version has to match the version of protoc used to generate code.

--
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 protobuf+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/protobuf/57e7fc88-b416-42e8-bd17-b42eaa8e73cf%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages