当前位置 : 主页 > 大数据 > 区块链 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-22
我一直致力于为项目实施IPC的protobufs.由于某种原因,未设置/序列化设置为0的值.对于上下文,.proto文件包含以下消息: syntax = "proto3";enum SetGet { SET = 0; GET = 1;}message State { SetGet setget = 1; d
我一直致力于为项目实施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文件,然后尝试运行以下测试脚本:

import filename_pb2 as pb

state = pb.State()
state.x = 0
state.y = 0
state.depth = 0
state.yaw = 0
state.pitch = 0
state.roll = 0
state.setget = pb.SET

print("State: {}".format(state))

state2 = pb.State()
state2.ParseFromString(state.SerializeToString())

print("State2: {}".format(state2))

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

State: 
State2:

似乎没有设置任何东西,或零值以某种方式被忽略.
但是,当我将值(x,y,深度等)更改为非零值(例如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

即使数字被打印出来,由于某种原因,枚举仍然不是.
为什么这会发生在protobufs上?默认情况下是double类型0,因此protobuf序列化程序会忽略它们来节省空间吗?那么,为什么在解析State2时它们没有被恢复?我错过了文档中的某些内容吗?提前致谢!

– 蒂姆

是,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.

网友评论