【发布时间】:2015-02-17 22:03:37
【问题描述】:
使用 Cython(充当接口,因此我可以通过 Python 调用基于 C++ 的函数),我试图包装 C++ 类的复杂层次结构,所有这些最终都继承自一个基类。这个单一的基类有许多虚函数,它们的实现根据所考虑的派生类而有所不同。派生类也有自己独特的功能。
我在通过 Cython 包装它时遇到了很多麻烦,主要是因为我找不到在每个继承的类中将 self.thisptr 重新定义为该特定类型的方法(而不是单数基类的类型)。我也尝试过类型转换,以及尝试删除指针然后重新初始化它,但它仍然认为它指向同一个基类。示例代码如下:
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):
#This is one of the solutions that I have tried
def __cinit__(self):
if(self.thisptr):
del self.thisptr
self.thisptr = new DerivedClass()
def __dealloc__(self):
del self.thisptr
def Evaluate(self, time):
#I need to call the Derived implementation of this function, not Base
return self.thisptr.Evaluate(self,time)
def SetObject(self, PyBaseClass inputObject):
#The issue here is that it looks for SetObject to be declared in BaseClass and spits an error otherwise. If I put a empty declaration, the complain is of ambiguous method overload
self.thisptr.SetObject(inputObject.thisptr)
另外,当我在我的 Python 脚本中调用 SetObject 时,我希望能够传入一个 PyDerived 对象作为输入,因为它继承自 PyBase,它不应该正常工作吗?我试过了,错误是:
参数类型不正确:预期 PyBase,得到 PyDerived
希望我的问题有意义,如果您需要任何其他信息,请告诉我:)
【问题讨论】:
标签: python c++ inheritance virtual cython