簡體   English   中英

Google Protobuf-C ++和Python之間的UDP通信-google.protobuf.message.DecodeError:解壓縮需要長度為4的字符串參數

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

下午好。

我正在嘗試在CPP中的一個框架和Python中的另一個框架之間發送消息。 我遵循以下所示的相同過程: 序列化C ++對象以通過套接字發送到Python-最佳方法?

我在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));

這肯定會導致您看到的錯誤。

我已經編輯了另一個問題以添加此修復程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM