如何确定 protobuf 中的消息类型,以便我可以使用该 type.parsefrom(byte[ ]) [英] How to determine message type in protobuf so that I can use that type.parsefrom(byte[ ])

查看:38
本文介绍了如何确定 protobuf 中的消息类型,以便我可以使用该 type.parsefrom(byte[ ])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I have multiple message types defined in .proto

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

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;

如何获得我添加到 buf 中的这种类型",以便我可以实现类似

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

MessageType parseFrom(byte[] data);

推荐答案

不清楚具体要求是什么.但是我假设您正在尝试发送不同类型的消息,并且接收方应该能够从接收到的字节中解析出正确的对象.这可以按以下示例所示完成:

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;
    }   
}

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

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"功能在旧版本的 protobuf 编译器上可能不可用.

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

这篇关于如何确定 protobuf 中的消息类型,以便我可以使用该 type.parsefrom(byte[ ])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆