5

I'm currently using two message protocols, one is google proto and the other is c-structs. What is the best solution to convert a google protocol buffer message (MessageLite) to a byte array?

I want, for example, to convert the following google proto message:

message GoogleRequest
{
     optional int32 request = 1 [default = 0];
}

to:

struct Request
{
    int request;
};

I have tried the following but it does not work:

GoogleRequest reqMsg;
reqMsg.set_request(1234);

int size = reqMsg.ByteSize();
Request* reqStruct = new Request;
reqMsg.SerializeToArray((void*)reqStruct , size);

Any suggestions, or is the best way just to do:

reqStruct->request = reqMsg.request();

I have a lot of message types and I would be awesome to find a generic way to do it.

1 Answer 1

15

You say you want to convert your message to a byte array, but your code suggests you're trying to convert it to a C struct (Request). Converting to a C struct is not supported. Converting to a byte array (that is, an array of char) is easy:

int size = reqMsg.ByteSize();
char* array = new char[size];
reqMsg.SerializeToArray(array, size);

Or, another way:

std::string bytes = reqMsg.SerializeAsString();
const char* array = bytes.data();
int size = bytes.size();

However, this array is not a struct, and it could have many different sizes depending on the content. There is no way to convert to a struct except to write code which copies over each field manually.

Sign up to request clarification or add additional context in comments.

1 Comment

In 2021, ByteSize has been replaced by ByteSizeLong: warning: ‘int google::protobuf::MessageLite::ByteSize() const’ is deprecated: Please use ByteSizeLong() instead [-Wdeprecated-declarations] Simply change your code to: long size = reqMsg.ByteSizeLong()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.