用于IO文件的Pybind11文件指针包装器

2024-04-19 15:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何在这里为构造函数编写包装器?你知道吗


Tags: 文件pytestloginitdefclassfile
1条回答
网友
1楼 · 发布于 2024-04-19 15:20:34

我相信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")
)

相关问题 更多 >