使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区 [英] Deserialize protobuf buffer in Python from C++ with pybind11

查看:372
本文介绍了使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a char *buffer which I convert to a C++ string std::string sbuffer(buffer); because I want to pass it to python.

C++ 可以用于:

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

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

I pass the buffer to python via:

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 文件看起来有点像这样:

The python file looks kinda like this:

import proto.protobuf_pb2


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

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

If I run the code I get the following error message:

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')?提前致谢.

Do I make some fundamental error or how can I solve the issue? Is it the encoding of sbuffer (when I don't encode i get the error: TypeError: memoryview: a bytes-like object is required, not 'str')? Thanks in advance.

推荐答案

我猜您想将缓冲区作为 bytes 传递.所以代替

I guess you want to pass your buffer as bytes. So instead of

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

你需要

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

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

Also change python interface to accept one argument.

这篇关于使用 pybind11 从 C++ 反序列化 Python 中的 protobuf 缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆