I am using Cython to wrap a set of C++ classes, allowing a Python interface to them. Example Code is provided below:
inheritTest.pyx:
cdef extern from "BaseClass.h":
cdef cppclass BaseClass:
BaseClass() except +
void SetName(string)
float Evaluate(float)
bool DataExists()
cdef extern from "DerivedClass.h":
cdef cppclass DerivedClass(BaseClass):
DerivedClass() except +
void MyFunction()
float Evaluate(float)
bool DataExists()
SetObject(BaseClass *)
cdef class PyBaseClass:
cdef BaseClass *thisptr
def __cinit__(self):
self.thisptr = new BaseClass()
def __dealloc__(self):
del self.thisptr
cdef class PyDerivedClass(PyBaseClass):
def __cinit__(self):
if(self.thisptr):
del self.thisptr
self.thisptr = new DerivedClass()
def __dealloc__(self):
del self.thisptr
def Evaluate(self, time):
return self.thisptr.Evaluate(self,time)
def SetObject(self, PyBaseClass inputObject):
# *** The issue is right here ***
self.thisptr.SetObject(<BaseClass *>inputObject.thisptr)I want to be able to call SetObject in Python similar to as shown below:
main.py:
from inheritTest import PyBaseClass as base
from inheritTest import PyDerivedClass as der
a = der()
b = der()
a.SetObject(b)I thought it would work since the classes inherit from each other, but its giving me the following error:
Argument has incorrect type: expected PyBaseClass, got PyDerivedClass
Not specifying type in the function definition makes it think that the inputObject is a pure Python object (has no C-based attributes, which it does), in which case the error is:
*Cannot convert Python object to BaseClass *
A sort-of hacky workaround to this just to have Python functions with different names that expect different types of arguments (ex: SetObjectWithBase, SetObjectWithDerived), and then within their implementation, just call the same C-based function having type-casted the input. I know for a fact this works, but I would like to avoid having to do this as much as possible. Even if there is a way I can catch the Type Error within the function, and deal with it inside, I think that might work, but I wasn't sure exactly how to implement that.
Hope this question makes sense, let me know if you require additional information.
Just wondering if this is a Cython bug, if not, how can I get around this
StackOverflow Link: http://stackoverflow.com/questions/28573479/cython-python-c-inheritance-passing-derived-class-as-argument-to-function-e/28615663#28615663