python - 使用 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'
?提前致谢。
解决方案
我猜你想将你的缓冲区作为bytes
. 所以而不是
calculation.attr("funcName")(sbuffer.data(), sbuffer.size());
你需要
calculation.attr("funcName")(py::bytes(sbuffer.data(), sbuffer.size()));
还要更改 python 接口以接受一个参数。
推荐阅读
- image - 如何在本地主机上设置正确的路径
- heroku - 无法在 Heroku 上使用 APScheduler 更新应用程序中的 GeoJSON 文件
- r - 将ggplot2 y轴修改为整数,不限制多个图的y轴
- mysql - TypeORM createQueryBuilder 无法管理 JOIN
- json - 如何解决:使用 gactions 时出现“没有“预览”的帮助主题”错误?
- css - 如何覆盖材料ui REACTjs中menuItem中选定的类?
- android - 在 FragmentPagerAdapter 上调用 instantiateItem 或 getItem
- windows - 指定域不存在或无法联系
- javascript - 获取输入字段值并将它们放入二维数组
- pandas - Python-将数据框导出到 csv