Google Protocol Buffer 3.0 - set_field(...) 后序列化长度为 0

Google Protocol Buffer 3.0 - Serialized Length Is 0 After set_field(...)

我正在使用 Google Protobuf 3.0.0。和 ZeroMQ 来实现服务器和一些客户端之间的连接。所以,我的原型文件看起来像这样:

// message Request{} omitted
message Response{
 enum MessageType{
   Type1 = 0;
   Type2 = 1;
   Type3 = 2;
 }
 enum ConfirmationCode{
   OK = 0;
   Error1 = 1;
   Error2 = 2;
 }
 MessageType Type = 1;
 repeated someField1 field1 = 2;
 // ... some code omitted
 ConfirmationCode Confirm = 3;
}

如您所见,在 ProtoBuf 3 中不再有 requiredoptional 字段,我不使用任何默认值。 现在,我 运行 在序列化一些 Protobuf 消息并尝试通过 ZMQ 发送它们时遇到了一些麻烦。 google::protobuf::message_lite::SerializeToString(...) 完成的序列化没有失败,但是这个方法和 google::protobuf::message_lite::SerializeAsString() 仍然产生空字符串,所以我认为在序列化之前我的响应中可能没有设置单个字段,我引入了一个类似于以下

void InitResponse(Response& resp)
{
  resp.set_confirm(Response_ConfirmationCode_OK);
  resp.set_type(Response_MessageType_Type1);
}

确保至少有一些字段存在。尽管如此,在调用此方法之前和之后,我的序列化响应的长度为 0。我也尝试使用 google::protobuf::Message::DebugString() 但我认为此方法不会打印存在的每个字段,因为我总是打印空字符串。

如果序列化没有失败,为什么我的序列化消息最终为空?

https://developers.google.com/protocol-buffers/docs/proto3#default

For enums, the default value is the first defined enum value, which must be 0.

您根本没有更改 InitResponse 中的默认值。尝试设置其他任何设置 :)