Reputation: 1
i have wrapped a simple c++ interface / class using pybind11
py::class_<IBaseObject, SmartPtr<IBaseObject>>(m, "BaseObject")
.def(py::init([]()
{
return BaseObject_Create();
}))
)
IBaseObject is interface, SmartPtr is custom holder type and BaseObject_Create is factory function which returns IBaseObject*.
Instatiating class from python works fine, however i also want to instantiate python wrapper class from C++ while passing IBaseObject* as parameter. Is this possible?
Upvotes: 0
Views: 1114
Reputation: 3533
If you just want to instantiate your class in your C++ binding code, you can use pybind
s Python C++ Interface:
https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object.html#calling-python-functions
Some ways to do this:
// Option 1: Use your existing class handle.
py::class_<IBaseObject, ...> py_cls(...);
py::object py_obj = py_cls();
// - Cast it if you need to.
auto* obj = py_obj.cast<IBaseObject*>();
// - or cast to `SmartPtr<IBaseObject>()` if its shareable.
// Option 2: Re-import elsewhere in your code.
py::object py_cls = py::module::import("my_pybind_module").attr("IBaseObject");
py::object py_obj = py_cls();
// - etc...
// Option 3: Use `eval` (blech)
py::module m = py::module::import("my_pybind_module");
py::object py_obj = py::eval("IBaseObject()", /* globals */ m.attr("__dict__"));
Upvotes: 0