使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区

Deserialize protobuf buffer in Python from C++ with pybind11

我有一个 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')?提前致谢。

我猜您想将缓冲区作为 bytes 传递。所以而不是

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

你需要

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

同时更改 python 界面以接受一个参数。

Source of py::bytes