Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google-protobuf: How to create unions using Google protocol buffer

I am currently trying to use Google Protocol Buffers for C language. I am a little unsure as to how to create a C union using GPB.

For example, with a proto file as follows:

message msgToSend
{
 required Type msg_type=1; //Type is a predefined enum to determine message type
 optional ReqMsg1 msg1=2;
 optional ReqMsg2 msg2=3;
}

I expect above to generate a union upon compilation but a structure is generated as follows:

struct _msgToSend
{
 ProtobufCMessage base;
 Type msg_type;
 ReqMsg1 msg1;
 ReqMsg2 msg2;
}
like image 921
Sphoorthi Dayanand Avatar asked Mar 10 '16 12:03

Sphoorthi Dayanand


People also ask

What is Google protocol buffer used for?

What are protocol buffers? Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler.

What is protocol buffer in gRPC?

Protocol Buffer, a.k.a. Protobuf Protobuf is the most commonly used IDL (Interface Definition Language) for gRPC. It's where you basically store your data and function contracts in the form of a proto file.

What is the difference between proto2 and Proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.


1 Answers

In protobuf there is a dedicated structure for that (I'm using it in C++ though, not sure if it will work in pure C):

message MyUnion {
    oneof MyUnionOneof {
        bool booleanValue = 1;
        string stringValue = 2;
    }
}

Check out this link: https://developers.google.com/protocol-buffers/docs/proto#oneof

like image 138
Quarra Avatar answered Sep 22 '22 08:09

Quarra