在协议缓冲区中定义字典 [英] Define dictionary in protocol buffer

查看:125
本文介绍了在协议缓冲区中定义字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的协议缓冲区和C ++,所以这可能是一个基本的问题,但我没有找到任何运气的答案。基本上,我想要在我的 .proto 文件中定义的字典的功能,像一个枚举。我正在使用协议缓冲区来发送数据,我想定义单位及其各自的名称。一个枚举将允许我定义单位,但我不知道如何映射人类可读的字符串。

I'm new to both protocol buffers and C++, so this may be a basic question, but I haven't had any luck finding answers. Basically, I want the functionality of a dictionary defined in my .proto file like an enum. I'm using the protocol buffer to send data, and I want to define units and their respective names. An enum would allow me to define the units, but I don't know how to map the human-readable strings to that.

作为我的意思的例子, .proto 文件可能如下所示:

As an example of what I mean, the .proto file might look something like:

message DataPack {
    // obviously not valid, but something like this
    dict UnitType {
        KmPerHour = "km/h";
        MiPerHour = "mph";
    }

    required int id = 1;
    repeated DataPoint pt = 2;

    message DataPoint {
        required int id = 1;
        required int value = 2;
        optional UnitType theunit = 3;
    }
}

然后有一些像创建/处理消息的东西:

and then have something like to create / handle messages:

// construct
DataPack pack;
pack->set_id(123);
DataPack::DataPoint pt = pack.add_point();
pt->set_id(456);
pt->set_value(789);
pt->set_unit(DataPack::UnitType::KmPerHour);

// read values
DataPack::UnitType theunit = pt.unit();
cout << theunit.name << endl; // print "km/h"

我可以定义一个枚举与单位名称,并写一个函数将它们映射到接收端的字符串,但是将它们定义在同一个位置更有意义,并且该解决方案似乎太复杂(至少对于有人最近被Python的便利弄坏了)。有一个更简单的方法来实现这一点吗?

I could just define an enum with the unit names and write a function to map them to strings on the receiving end, but it would make more sense to have them defined in the same spot, and that solution seems too complicated (at least, for someone who has lately been spoiled by the conveniences of Python). Is there an easier way to accomplish this?

推荐答案

您可以使用自定义选项将字符串与每个枚举成员相关联:
https://developers.google.com/protocol-buffers/docs/proto #options

You could use custom options to associate a string with each enum member: https://developers.google.com/protocol-buffers/docs/proto#options

在.proto中看起来像这样:

It would look like this in the .proto:

extend google.protobuf.FieldOptions {
  optional string name = 12345;
}

enum UnitType {
    KmPerHour = 1 [(name) = "km/h"];
    MiPerHour = 2 [(name) = "mph"];
}

不过,请注意,某些第三方protobuf库不了解这些选项。

Beware, though, that some third-party protobuf libraries don't understand these options.

这篇关于在协议缓冲区中定义字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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