如何用 pybind11 包装 std::istream 和 std::ostream?

时间:2021-07-22 18:31:32

标签: c++ pybind11

我在 cpp 中有两个函数可以获取我的类的状态并从我的类中读取状态。

writeBinary(std::ostream& s) 
readBinary(std::istream& s)

我想要一个我可以做的python函数

binary_state = class_a.writeBinary()
class_b = class_a.readBinary(binary_state)
class_a == class_b

我一直在尝试让 pybind11 处理这个问题。我试图有一个 writeBinary 将返回字符串的包装器,但我没有运气。 这是我尝试将 osstream 转换为字符串的内容

std::string writeBinaryWrapper(){
       std::stringstream binary_outfile;
       writeBinary(binary_outfile)
       return binary_outfile.str();
}

但是我在这次尝试中遇到了 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 143: invalid start byte 错误。 而且我想不出用 std::ostream 或 std::istream 包装 pybind11 的方法。

    .def("writeBinary", []() {
        std::ostringstream out;
        py::scoped_ostream_redirect redirect{
            out,
            py::module_::import("io").attr("BytesIO") // Python output
        };
        class::writeBinary()
    });

谁能帮我解决这个问题?如何获得 pybind 以便我可以将类写入二进制,然后从二进制读取以重新创建类?

0 个答案:

没有答案
相关问题