我正在开发 zmq/protobuf 应用程序,我在反序列化从 C++ 发送到 python 的消息时遇到问题。我很容易处理从 python 到 C++ 的消息,但是在另一个方向上我遇到了问题。
python 客户端应用程序中的 Protobuf 库提示它检测到:
文件“C:\Python27\lib\site-packages\google\protobuf\internal\python_message.py”,第 844 行,在 MergeFromString 中
raise message_mod.DecodeError('Unexpected end-group tag.')
我认为 C++ 序列化和 Python 反序列化之间存在问题。我想知道 C/C++ 中的空终止符是否存在问题。
我正在使用运行 Raspian 的 RaspberryPi 来编写 C++ 代码,并使用运行 Windows 7 的 x64 CPU 来编写 python 代码。
这是我的 C++ 序列化代码..
// Test Code.
// Try to send some 'demo' response back.
RPiProtocol::Message response;
std::string response_string;
response.set_type(RPiProtocol::Message::RESPONSE);
response.set_command(RPiProtocol::Message::GET_SYS_INFO);
response.set_version(0);
// Serialize ZMQ message to string.
if (response.SerializeToString(&response_string))
{
// Send response message back to the client.
zmq::message_t reply(response_string.length());
memcpy((void *)reply.data(), (void *)&response_string, response_string.length());
socket.send(reply);
}
这是我的 python 反序列化代码..
# Get the reply.
message = socket.recv()
response = rpi_protocol_pb2.Message()
# This line fails.
response.ParseFromString(str(message))
我在这个函数中调试反序列化失败 \google\protobuf\internal\python_message.py
def InternalParse(self, buffer, pos, end):
self._Modified()
field_dict = self._fields
unknown_field_list = self._unknown_fields
while pos != end:
(tag_bytes, new_pos) = local_ReadTag(buffer, pos)
field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None))
if field_decoder is None:
value_start_pos = new_pos
new_pos = local_SkipField(buffer, new_pos, end, tag_bytes)
if new_pos == -1: # HERE I HAVE -1 !!!
return pos
if not unknown_field_list:
unknown_field_list = self._unknown_fields = []
unknown_field_list.append((tag_bytes, buffer[value_start_pos:new_pos]))
pos = new_pos
else:
pos = field_decoder(buffer, new_pos, end, self, field_dict)
if field_desc:
self._UpdateOneofState(field_desc)
return pos
cls._InternalParse = InternalParse
你能帮我启用我的应用程序吗?
最佳答案
我在 python 中反序列化 protobuff 数据时也遇到了问题。 protobuff 数据已使用“C”protobuff 代码序列化。
简短的回答是查看使用 binascii.unhexlify()。
在 python 上序列化一个 protobuff 并发送到它被反序列化的“C”代码工作得很好。但在我执行以下操作之前,情况并非如此:binstring = binascii.unhexlify(hexstring)。然后 protoBuff.ParseFromString(binstring) 工作得很好。
关于python - 消息反序列化期间 python 中的 Protobuf 提示 'Unexpected end-group tag.',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31393364/