簡體   English   中英

使用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' )? 提前致謝。

我猜你想以bytesbytes傳遞緩沖區。 所以代替

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

你需要

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

同時更改python接口以接受一個參數。

py::bytes來源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM