为什么我的Protobuf消息(在Python中)忽略零值?

2024-09-29 19:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为一个项目实现IPC的protobufs。由于某些原因,未设置/序列化设置为0的值。对于上下文,.proto文件包含以下消息:

syntax = "proto3";

enum SetGet {
    SET = 0;
    GET = 1;
}

message State {
    SetGet setget = 1;
    double x = 2;
    double y = 3;
    double depth = 4;
    double yaw = 5;
    double pitch = 6;
    double roll = 7; 
}

我用protoc将文件编译成Pythonpb2文件,然后尝试运行以下测试脚本:

^{pr2}$

运行它时,将打印以下输出:

State: 
State2: 

似乎什么都没有设置,或者零值被忽略了。 但是,当我将值(x、y、depth等)更改为非零值(比如0.1)时,会得到以下预期结果:

State: x: 0.1
y: 0.1
depth: 0.1
yaw: 0.1
pitch: 0.1
roll: 0.1

State2: x: 0.1
y: 0.1
depth: 0.1
yaw: 0.1
pitch: 0.1
roll: 0.1

即使数字被打印出来,由于某些原因,枚举仍然没有。 为什么这种情况会发生在原生生物身上?默认情况下是双精度类型0,因此protobuf序列化程序会忽略它们来节省空间?那么,为什么在解析State2时不恢复它们呢?文档中是否有我遗漏的行?提前谢谢!在

--蒂姆


Tags: 文件项目序列化情况原因ipcstatedouble
2条回答

是的,默认值为0。在the documentation中明确提到了这种情况:

Note that for scalar message fields, once a message is parsed there's no way of telling whether a field was explicitly set to the default value (for example whether a boolean was set to false) or just not set at all: you should bear this in mind when defining your message types. For example, don't have a boolean that switches on some behaviour when set to false if you don't want that behaviour to also happen by default. Also note that if a scalar message field is set to its default, the value will not be serialized on the wire.

在protobuf中,零是数字的默认值,空字符串是字符串的默认值。为了提高效率,默认值不会通过导线传输。在

如果您真的想知道它是否被显式设置,请不要在实际操作中使用默认的零:

enum SetGet {
    NONE = 0;
    SET = 1;
    GET = 2;
}

请记住,这将导致网络上的额外通信量,而且,由于您只关心要打印的内容,您也可以理解零是默认值,或者编写自己的自己的打印例程来输出所有内容。在

相关问题 更多 >

    热门问题