首页 > 解决方案 > 使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区

问题描述

我有一个char *buffer我转换为 C++ 字符串的字符串std::string sbuffer(buffer);,因为我想将它传递给 python。

C++ 可以使用:

protoObj.ParseFromArray(buffer, sbuffer.size());

我通过以下方式传递buffer给python:

py::scoped_interpreter python;
py::module calc = py::module::import("Calculation"); 
py::object Calculation = calc.attr("Calculation");
py::object calculation = Calculation();
calculation.attr("funcName")(sbuffer.data(), sbuffer.size());

python文件看起来有点像这样:

import proto.protobuf_pb2


class Calculation:
    def funcName(self, sbuffer, sbuffer_size):
        protoObj = ProtoBuffClass()
        protoObj.ParseFromString(sbuffer.encode('utf-8'))

如果我运行代码,我会收到以下错误消息:

terminate called after throwing an instance of 'pybind11::error_already_set'
  what():  DecodeError: Truncated message.

At:
  /usr/local/lib/python3.6/dist-packages/google/protobuf/internal/decoder.py(721): DecodeField
  /usr/local/lib/python3.6/dist-packages/google/protobuf/internal/python_message.py(1189): InternalParse
  /usr/local/lib/python3.6/dist-packages/google/protobuf/internal/python_message.py(1132): MergeFromString
  /usr/local/lib/python3.6/dist-packages/google/protobuf/message.py(187): ParseFromString
  ./Calculation.py(31): funcName

Aborted (core dumped)

我是否犯了一些基本错误或者我该如何解决这个问题?是 sbuffer 的编码吗(当我不编码时,我得到错误:)TypeError: memoryview: a bytes-like object is required, not 'str'?提前致谢。

标签: pythonc++protocol-bufferspybind11

解决方案


我猜你想将你的缓冲区作为bytes. 所以而不是

calculation.attr("funcName")(sbuffer.data(), sbuffer.size());

你需要

calculation.attr("funcName")(py::bytes(sbuffer.data(), sbuffer.size()));

还要更改 python 接口以接受一个参数。

来源py::bytes


推荐阅读