首页 > 解决方案 > _IO_FILE 的 Pybind11 文件指针包装器

问题描述

我正在为接受文件指针的 c++ 类编写 python 绑定 -

  PYBIND11_MODULE(pywrapper, m) { 
...
 py::class_<Dog, Animal>(m, "Dog")
        .def(py::init<FILE * const>());

}

我这样调用c++函数-

f = open("test.log","w")

c = Dog(f)

我收到了预期的错误-

File "main.py", line 6, in test_init
    client = Dog(f)
TypeError: __init__(): incompatible constructor arguments. The following argument types are supported:
    1. pywrapper.Dog(arg0: _IO_FILE)

Invoked with: <_io.TextIOWrapper name='test.log' mode='w' encoding='UTF-8'>

我如何在这里为构造函数编写包装器?

标签: pythonc++pybind11

解决方案


我相信输入缓冲区没有在 pybind11 中实现。这是输出缓冲区的实现https://github.com/pybind/pybind11/blob/master/include/pybind11/iostream.h#L24

以下是使用缓冲区作为输出流的示例:

.def("read_from_file_like_object",
   [](MyClass&, py::object fileHandle) {

     if (!(py::hasattr(fileHandle,"write") &&
         py::hasattr(fileHandle,"flush") )){
       throw py::type_error("MyClass::read_from_file_like_object(file): incompatible function argument:  `file` must be a file-like object, but `"
                                +(std::string)(py::repr(fileHandle))+"` provided"
       );
     }
     py::detail::pythonbuf buf(fileHandle);
     std::ostream stream(&buf);
     //... use the stream 

   },
   py::arg("buf")
)

推荐阅读