Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pybind11 File pointer wrapper for _IO_FILE

I am writing a python binding for c++ class that accepts a file pointer -

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

}

I am calling the c++ function like this -

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

c = Dog(f)

I am getting an error as expected -

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'>

How can i write the wrapper for constructor here?

like image 224
blue01 Avatar asked Sep 13 '25 05:09

blue01


1 Answers

I believe input buffers are not implemented in pybind11. Here is implementation of output buffer https://github.com/pybind/pybind11/blob/master/include/pybind11/iostream.h#L24

Here is example of usage of buffer as output stream:

.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")
)
like image 61
Sergei Avatar answered Sep 15 '25 20:09

Sergei