Premises: I am not at all a C++ expert and I checked similar questions such as this and references therein but without much success...
I am developing Python bindings with pybind11 for a C++ project of which I am not the author. Such a project implements a File Data Format.
One of the classes I managed to expose to Python is the one that implements the File object. The class header looks something like this (among many other things),
/// Open a disk file in the specified mode
XCDFFile(const char *fileName,
const char *mode)
{
Init();
Open(fileName, mode);
}
XCDFFile()
{
Init();
}
~XCDFFile()
{
// Close-on-destruction behavior prevents assignment/copy construction
Close();
}
I managed to do (among other things)
py::class_<XCDFFile>(m, "File")
.def(py::init<const char *, const char *>())
[...]
.def("__iter__", [](XCDFFile &self)
{ return &self; })
.def("__enter__", [](XCDFFile &self)
{ return &self; })
But I don't know how __exit__
should look like in this syntax.
Python docs say it should look like object.__exit__(self, exc_type, exc_value, traceback)
, but I don't know how to translate this into pybind11, hoping that the class I am trying to expose doesn't need to be modified.
With the solution above I indeed receive the following error,
TypeError Traceback (most recent call last)
Input In [2], in <cell line: 1>()
----> 1 with File("test_file_for_pybindings.xcd", "r") as input_file:
2 pass
TypeError: __exit__(): incompatible function arguments. The following argument types are supported:
1. (self: xcdf.xcdf.File) -> None
Invoked with: <xcdf.xcdf.File object at 0x10f430330>, None, None, None