首页 > 解决方案 > Protobug 消息中的消息标识符

问题描述

有没有办法获得类似 protobuf 消息的 ID 的东西。

例如我有:

syntax = "proto3";

package protobuf;

message parameters_t
{
    string audio_device = 1;
}

message master_t
{
    enum type_t
    {
        unknown = 0;
        login_rsp = 1;
    }

    type_t type = 1;
}

我想在 C++ 中做的是通过线路发送大小,然后是消息的一些 ID 和缓冲区。

例如paramters_t是 ID 0(静态可访问)并且master_t是 ID 1,所以我可以在我的代码中做:

if (id == protobuf::master_t::id) {
    ...
}
else if (id == protobuf::paramters_t::id) {
    ...
}

有没有办法在不手动分配值的情况下实现这一点?我希望以某种方式将其设置在原型文件中。它可以是我自己定义的常数,我不在乎。

标签: c++protocol-buffers

解决方案


一种典型的方法是只定义一个枚举:

enum MsgId {
  MSGID_MASTER = 0;
  MSGID_PARAMETERS = 1;
}

然后,您可以像常量一样在 C++ 中访问它们。


推荐阅读