java 如何确定 protobuf 中的消息类型,以便我可以使用该 type.parsefrom(byte[ ])

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30564404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:19:31  来源:igfitidea点击:

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

javaprotocol-buffers

提问by android.developer

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

我正在尝试将 protobuf 数据从 cpp 端发送到 java 端。

I have multiple message types defined in .proto

我在 .proto 中定义了多种消息类型

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

在 Cpp 方面,我对每种消息类型都有枚举,并将其添加到 buf 输出中,如下所示:

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

我如何获得我添加到 buf 的这种“类型”,以便我可以实现类似的目标

MessageType parseFrom(byte[] data);

回答by Nipun Talukdar

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.

基本上,始终 WrapperMessage 对象通过包装 Message1 或 Message2 对象的线路发送。然后在接收端,我们可以先解析 WrapperMessage 对象,然后使用 HasField 方法检查包装对象中是否存在 m1 或 m2 字段,然后从中解析出 Message1 或 Message2 对象。

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

“oneof”功能在旧版本的 protobuf 编译器上可能不可用。

回答by Philip Nelson

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

Protobuf 3 引入了一个新概念Any来处理这个问题。一个很好的描述可以在这里找到。