Google Protobuf3 消息中的多个字符串问题

Google Protobuf3 Multiple string in message issue

我有一条消息看起来像:

message Connected {
  sint32 xloc   = 1; // x spawn world position
  sint32 yloc   = 2; // y spawn world position
  sint32 zrot   = 3; // z spawn rotation
  string sector = 4; // sector name (unsure about this)
  string name   = 5; // player name
  string pid    = 6; // player id
  string scolor = 7; // ship color
  string sname  = 8; // ship name
}

我正在尝试在我的 C++ 代码中初始化它,如下所示:

server::player::Connected connectMessage; // send this to this joining client
connectMessage.set_name("clientName");
connectMessage.set_pid("clientId");
connectMessage.set_scolor("shipColor");
connectMessage.set_sname("shipName");
connectMessage.set_xloc(0);
connectMessage.set_yloc(0);
connectMessage.set_zrot(0);

出于某种原因,当我设置我的字符串参数时,之前的字符串被设置为该字符串值。所以,如果我执行 set_pid,名称字段也会更改为 pid。 set_scolor 名称和 pid 将设置为 s_color。 set_sname 名称、pid 和 scolor 将更改为 sname。似乎它们都共享相同的字符串指针字段位置。

每个字符串字段执行后的结果将是"shipName"。

我没有正确初始化消息吗?或者我需要在这里做些不同的事情吗?当我从编码流中序列化我的消息时,我得到了预期的消息,但手动创建似乎与我当前正在尝试做的事情无关。

非常感谢您提供的信息。

更改为对我的字符串使用重复字段似乎解决了问题。

message Connected {
  sint32 xloc = 1; // x spawn world position
  sint32 yloc = 2; // y spawn world position
  sint32 zrot = 3; // z spawn rotation
  // [0] => username
  // [1] => userid
  // [2] => shipcolor
  // [3] => shipname
  repeated string userinfo = 4;
}

有了这个,我可以手动将新字符串添加到重复字符串列表中。

server::player::Connected connectMessage;
connectMessage.set_xloc(stats.m_xPos);
connectMessage.set_yloc(stats.m_yPos);
connectMessage.set_zrot(stats.m_zRot);
// [0] => username
connectMessage.add_userinfo();
connectMessage.set_userinfo(0, stats.m_clientName);
// [1] => userid
connectMessage.add_userinfo();
connectMessage.set_userinfo(1, stats.m_clientId);
// [2] => shipcolor
connectMessage.add_userinfo();
connectMessage.set_userinfo(2, stats.m_shipColor);
// [3] => shipname
connectMessage.add_userinfo();
connectMessage.set_userinfo(3, stats.m_shipName);

它确实允许更清晰的 .proto 文件,但奇怪的是,仅使用单个字符串会导致问题。