I have a Python class, which is derived from a C++ class and overrides part of the functions. A C++ function receives an object of the Python class and stores it in a vector, so the Python class should not be collected by the GC. I tried two different approaches, but first one doesn't compile and second doesn't see the overrides at run time (the functions of C++ are called instead of the Python class functions). Please tell me what is the right way to do this.
The C++ code:
class MyClass
{
public:
virtual void PureVirtual(int i) = 0;
virtual const char* VirtualWithDefaultImpl()
{
return "MyClass";
}
};
void MyFnc(boost::shared_ptr<MyClass> obj)
{
myVector.push_back(obj);
std::cout << obj->VirtualWithDefaultImpl() << std::endl;
obj->PureVirtual(0);
}
The python wrapper:
class MyClassWrap : public MyClass, wrapper<MyClass>
{
public:
MyClassWrap(PyObject* self) : m_self(self)
{
Py_INCREF(self);
}
MyClassWrap(PyObject* self, const MyClass& other) : MyClass(other), m_self(self)
{
Py_INCREF(self);
}
~MyClassWrap()
{
Py_DECREF(m_self);
}
virtual void PureVirtual(int i)
{
this->get_override("PureVirtual")(i);
}
virtual const char* VirtualWithDefaultImpl()
{
if (override f = this->get_override("VirtualWithDefaultImpl"))
return f();
return MyClass::VirtualWithDefaultImpl();
}
const char* DefaultVirtualWithDefaultImpl()
{
return this->MyClass::VirtualWithDefaultImpl();
}
private:
PyObject* m_self;
};
BOOST_PYTHON_MODULE(MyModule)
{
// First approach:
// Fails in compilation with error C2243: 'type cast' : conversion from
// 'MyClassWrap *' to 'boost::python::wrapper<T> *' exists, but is inaccessible
//class_<MyClassWrap, boost::shared_ptr<MyClassWrap>, boost::noncopyable>("MyClass")
// Second approach:
// Doesn't see the overrides at runtime
class_<MyClass, boost::shared_ptr<MyClassWrap>, boost::noncopyable>("MyClass")
.def("PureVirtual", pure_virtual(&MyClass::PureVirtual), args("i"))
.def("VirtualWithDefaultImpl", &MyClass::VirtualWithDefaultImpl,
&MyClassWrap::DefaultVirtualWithDefaultImpl);
def("MyFnc", &MyFnc, args("obj"));
}
The Python code:
class PythonDerived(MyModule.MyClass):
def PureVirtual(self, i):
print i
def VirtualWithDefaultImpl(self):
return 'PythonDerived'
MyModule.MyFnc(PythonDerived())
Output of the second approach run. As you can see the functions of MyClass are called instead of the PythonDerived functions:
MyClass
File "z:\tmp\tmp.py", line 11, in <module>
MyModule.MyFnc(PythonDerived())
TypeError: 'NoneType' object is not callable
I have modified your wrapper class and how it is exposed to python and now that is working as expected:
Output: