【问题标题】:Pybind11 File pointer wrapper for _IO_FILE_IO_FILE 的 Pybind11 文件指针包装器
【发布时间】:2019-05-30 22:40:50
【问题描述】:

我正在为接受文件指针的 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'>

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

【问题讨论】:

  • 真的没有办法让它工作吗?无论如何,对于这个有趣的问题,获得一个被接受且正确的答案是一件好事。

标签: python c++ pybind11


【解决方案1】:

我相信 input 缓冲区没有在 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")
)

【讨论】:

  • ostream 对象不会写入到文件而不是从中读取吗?
猜你喜欢
  • 2021-09-18
  • 2022-07-06
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多