'pybind11: Access violation, no RTTI data, when casting void* to pointer to previously registered class and returning it to python
I am running into an issue where I try to cast a void* to a pointer to a previously registered class MtDTI<MtObject>*, and returning that pointer to the python side. The function is a simple wrapper function, that only casts the pointer like such:
m.def("to_mt_dti", [](void* obj) {
return static_cast<MtDTI<MtObject>*>(obj);
}, py::return_value_policy::reference);
However when I try to run the following code in Python:
dti = test.to_mt_dti(obj) # test is the pybind11 module
I get an exception saying RuntimeError: Access violation - no RTTI data!, stemming from that line.
For reference, the obj variable is a void* that was previously passed to Python from the C++ side, and is a pointer to static memory, which is why I also specify py::return_value_policy::reference, to make sure Python doesn't try to deallocate it once it goes out of scope.
The class is registered like so:
py::class_<MtDTI<MtObject>>(m, "MtDTI")
.def(py::init([](MtDTI<MtObject>* obj) { return obj; }), py::return_value_policy::reference)
.def(py::init([](void* obj) { return static_cast<MtDTI<MtObject>*>(obj); }), py::return_value_policy::reference)
// And some more general member functions
As you can see the class has a constructor defined for both MtDTI<MtObject>* as well as void* directly. As far as I'm aware, pybind11 should be able to auto-convert from pointer to the class if that class has been registered before.
I am working in Visual Studio 2022 17.1.1, Using Python 3.9.5 with pybind11 Version 2.9.1.
I should also mention that this is an embedded module, and the Python code is run using py::eval_file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
