Google Protobuf - UDP Communication Between C++ and Python - google.protobuf.message.DecodeError: unpack requires a string argument of length 4

Google Protobuf - UDP Communication Between C++ and Python - google.protobuf.message.DecodeError: unpack requires a string argument of length 4

下午好。

我正在尝试在 CPP 中的一个框架和 Python 中的另一个框架之间发送消息。我遵循了以下所示的相同过程: Serialize C++ object to send via sockets to Python - best approach?

我在 Python 中的服务器代码是:

import socket
from DiceData_pb2 import DiceData

UDP_PORT=1555

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("", UDP_PORT))

dicedata = DiceData()
while True:
    data, addr = sock.recvfrom(1024)
    print data
    dicedata.ParseFromString(data)
    print ("gyrox = {0}".format(dicedata.gyrox))
    print("gyroy = {0}".format(dicedata.gyrox))
    print("gyroz = {0}".format(dicedata.gyroz))
    print("accelx = {0}".format(dicedata.accelx))
    print("accely = {0}".format(dicedata.accely))
    print("accelz = {0}".format(dicedata.accelz))
    print("roll = {0}".format(dicedata.roll))
    print("pitch = {0}".format(dicedata.pitch))
    print("yaw = {0}".format(dicedata.yaw))
    print("side = {0}".format(dicedata.side))
    print("certainty = {0}".format(dicedata.certainty))
    print("time = {0}".format(dicedata.time))

.proto 文件如下:

package prototest;

message DiceData {
  required float gyrox = 1;
  required float gyroy = 2;
  required float gyroz = 3;
  required float accelx = 4;
  required float accely = 5;
  required float accelz = 6;
  required float roll = 7;
  required float pitch = 8;
  required float yaw = 9;
  required int32 side = 10;
  required float certainty = 11;
  required string time = 12;
}

我知道通信正常,因为服务器收到第一条消息并将其打印为垃圾。但是,在到达 ParseFromString 行后,会发生以下错误:

Traceback (most recent call last):
  File "server.py", line 13, in <module>
    dicedata.ParseFromString(data)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/message.py", line 185, in ParseFromString
    self.MergeFromString(serialized)
  File "/usr/local/lib/python2.7/dist-packages/google/protobuf/internal/python_message.py", line 1095, in MergeFromString
    raise message_mod.DecodeError(e)
google.protobuf.message.DecodeError: unpack requires a string argument of length 4

有谁知道我该如何解决这个问题?我知道字符串不为空,因为前一行打印了垃圾,但我似乎无法将字符串转换回数据结构。

您链接到的问题中的 C++ 代码已损坏。它包含这一行:

sendto(sock, buf.data(), strlen(buf.c_str()), 0, (struct sockaddr *)&addr, sizeof(addr));

这是错误的!它将在第一个零值字节处切断消息。它应该看起来像这样:

sendto(sock, buf.data(), buf.size(), 0, (struct sockaddr *)&addr, sizeof(addr));

这肯定会导致您看到的错误。

我已经编辑了其他问题以添加此修复程序。