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

时间:2019-07-16 15:01:09

标签: python c++ protocol-buffers 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')?预先感谢。

1 个答案:

答案 0 :(得分:1)

我猜您想将缓冲区作为bytes传递。因此,而不是

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

您需要

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

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

Source of py::bytes