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?
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")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With