Define dictionary in protocol buffer

放肆的年华 提交于 2019-11-30 17:15:52

问题


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.

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"

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?


回答1:


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

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

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



来源:https://stackoverflow.com/questions/11474416/define-dictionary-in-protocol-buffer

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