How to determine message type in protobuf so that I can use that type.parsefrom(byte[ ])

非 Y 不嫁゛ 提交于 2019-12-04 17:42:11

问题


I am trying to send protobuf data from cpp side to java side.

I have multiple message types defined in .proto

On Cpp side, I have enums for every message type and I am adding it to the buf output as follows:

uint8_t* __temp = (uint8_t*)(buf);
*__temp++ = (type) >> 8;
*__temp = (type) & 0x00FF;

How do I get this 'type' that I have added to the buf, so that I can achieve something like

MessageType parseFrom(byte[] data);

回答1:


It is not clear what is the exact requirement. But I assume you are trying to send different types of messages and the the receiver should be able to parse the correct object out of the received bytes. This can be done as shown in the example below:

message Message1 {
   required string a = 1;
   required string b = 2;
}

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




message WrapperMessage {
    required int64 commonField = 1;
    oneof msg {
        Message1 m1 = 2;
        Message2 m2 = 3;
    }   
}

Basically, always WrapperMessage object is sent over the wire which wraps a Message1 or Message2 object. Then on the receiving side we may parse the WrapperMessage object first and then use HasField method to check if m1 or m2 fields is present in the wrapped object and then parse the Message1 or Message2 object out of it.

"oneof" feature may not be available on older version of protobuf compiler.




回答2:


Protobuf 3 introduced a new concept, Any, that handles this. A good description can be found here.



来源:https://stackoverflow.com/questions/30564404/how-to-determine-message-type-in-protobuf-so-that-i-can-use-that-type-parsefrom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!