我正在使用Cython来包装一组C ++类,允许它们使用Python接口。示例代码如下:
BaseClass.h:
#ifndef __BaseClass__
#define __BaseClass__
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
class BaseClass
{
public:
BaseClass(){};
virtual ~BaseClass(){};
virtual void SetName(string name){printf("in base set name\n");}
virtual float Evaluate(float time){printf("in base Evaluate\n");return 0;}
virtual bool DataExists(){printf("in base data exists\n");return false;}
};
#endif /* defined(__BaseClass__) */
DerivedClass.h:
#ifndef __DerivedClass__
#define __DerivedClass__
#include "BaseClass.h"
class DerivedClass:public BaseClass
{
public:
DerivedClass(){};
virtual ~DerivedClass(){};
virtual float Evaluate(float time){printf("in derived Evaluate\n");return 1;}
virtual bool DataExists(){printf("in derived data exists\n");return true;}
virtual void MyFunction(){printf("in my function\n");}
virtual void SetObject(BaseClass *input){printf("in set object\n");}
};
#endif /* defined(__DerivedClass__) */
NextDerivedClass.h:
#ifndef __NextDerivedClass__
#define __NextDerivedClass__
#include "DerivedClass.h"
class NextDerivedClass:public DerivedClass
{
public:
NextDerivedClass(){};
virtual ~NextDerivedClass(){};
virtual void SetObject(BaseClass *input){printf("in set object of next derived class\n");}
};
#endif /* defined(__NextDerivedClass__) */
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()
void SetObject(BaseClass *)
cdef extern from "NextDerivedClass.h":
cdef cppclass NextDerivedClass(DerivedClass):
NextDerivedClass() except +
# *** The issue is right here ***
void SetObject(BaseClass *)
cdef class PyBaseClass:
cdef BaseClass *thisptr
def __cinit__(self):
if type(self) is PyBaseClass:
self.thisptr = new BaseClass()
def __dealloc__(self):
if type(self) is PyBaseClass:
del self.thisptr
cdef class PyDerivedClass(PyBaseClass):
cdef DerivedClass *derivedptr
def __cinit__(self):
self.derivedptr = self.thisptr = new DerivedClass()
def __dealloc__(self):
del self.derivedptr
# def Evaluate(self, time):
# return self.derivedptr.Evaluate(time)
def SetObject(self, PyBaseClass inputObject):
self.derivedptr.SetObject(<BaseClass *>inputObject.thisptr)
cdef class PyNextDerivedClass(PyDerivedClass):
cdef NextDerivedClass *nextDerivedptr
def __cinit__(self):
self.nextDerivedptr = self.thisptr = new NextDerivedClass()
def __dealloc__(self):
del self.nextDerivedptr
def SetObject(self, PyBaseClass input):
self.nextDerivedptr.SetObject(<BaseClass *>input.thisptr)
我希望能够在Python中调用SetObject,类似于如下所示:
main.py:
from inheritTest import PyBaseClass as base
from inheritTest import PyDerivedClass as der
from inheritTest import PyNextDerivedClass as nextDer
#This works now!
a = der()
b = der()
a.SetObject(b)
#This doesn't work -- keeping the function declaration causes a overloaded error, not keeping it means the call below works, but it calls the inherited implementation (From derived class)
c = nextDer()
c.SetObject(b)
我认为它会起作用,因为类继承了彼此,但是它给了我以下错误:
参数类型不正确:预期PyBaseClass,得到PyDerivedClass
不在函数定义中指定类型使得它认为inputObject是纯Python对象(它没有基于C的属性),在这种情况下错误是:
*无法将Python对象转换为BaseClass *
一种简单的解决方法,只是为了让Python函数具有不同的名称,期望不同类型的参数(例如:SetObjectWithBase,SetObjectWithDerived),然后在它们的实现中,只需调用具有类型的相同的基于C的函数 - 投入了输入。我知道这是有效的,但我希望尽可能避免这样做。即使有一种方法我可以在函数中捕获类型错误,并在里面处理它,我认为这可能有效,但我不确定如何实现它。
希望这个问题有意义,如果您需要其他信息,请告诉我。
****编辑**** :代码已经过编辑,基本继承有效。在更多地使用它之后,我意识到多个继承级别的问题正在发生,例如,请参阅上面的编辑代码。基本上,为NextDerivedClass保留SetObject的声明会导致“不明确的重载方法”错误,不保留它允许我调用对象上的函数,但它调用继承的实现(来自DerivedClass)。 **
答案 0 :(得分:13)
经过以下答案和实验的大量帮助后,我想我明白了如何在Cython中实现基本继承,我回答了我自己的问题来验证/提高我的理解,并希望能帮助我任何未来可能遇到相关问题的人。如果此解释有任何问题,请随时在下面的评论中纠正我,我将对其进行编辑。我不认为这是唯一的方法,所以我确定其他方法有效,但这对我有用。
概述/所学到的东西:
所以基本上,从我的理解,Cython足够聪明(给定适当的信息)遍历继承hiearchy / tree并根据你调用它的对象的类型调用虚函数的适当实现
重要的是尝试镜像您尝试在.pyx文件中包装的C ++继承结构。这意味着确保:
1)导入的C ++ / Cython cppclasses(声明为cdef extern from
的cppclasses)以与实际C ++类相同的方式相互继承
2)只为每个导入的类声明了唯一的方法/成员变量(对于在两个类中以不同方式实现的虚函数,BaseClass
和DerivedClass
都不应该有函数声明。只要一个继承自另一个,函数声明只需要在Base导入的类中。
3)Python包装类(即。PyBaseClass
/ PyDerivedClass
)也应该以与实际C ++类相同的方式相互继承
4)与上面类似,虚拟函数的接口只需要存在于PyBase
包装器类中(不应该放在这两个类中,实际运行代码时会调用正确的实现)
5)对于每个子包或继承的Python包装类,您需要if type(self) is class-name:
和__cinit__()
函数进行__dealloc__()
检查。这样可以防止出现seg-fault等问题。您不需要检查&#34; leaf-nodes&#34;在hiearchy树(赢得或继承的类)
6)确保在__dealloc__()
函数中,只删除当前指针(而不是任何继承的指针)
7)同样,在__cinit__()
中,对于继承的类,确保设置当前指针,以及指向您要创建的类型的对象的所有派生指针(即{{1}。 })
希望以上几点在您看到下面的代码时非常有意义,这可以编译并运行/工作,因为我需要/打算工作。
BaseClass.h:
*self.nextDerivedptr = self.derivedptr = self.thisptr = new NextDerivedClass()*
DerivedClass.h:
#ifndef __BaseClass__
#define __BaseClass__
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
class BaseClass
{
public:
BaseClass(){};
virtual ~BaseClass(){};
virtual void SetName(string name){printf("BASE: in set name\n");}
virtual float Evaluate(float time){printf("BASE: in Evaluate\n");return 0;}
virtual bool DataExists(){printf("BASE: in data exists\n");return false;}
};
#endif /* defined(__BaseClass__) */
NextDerivedClass.h:
#ifndef __DerivedClass__
#define __DerivedClass__
#include "BaseClass.h"
#include "string.h"
using namespace std;
class DerivedClass:public BaseClass
{
public:
DerivedClass(){};
virtual ~DerivedClass(){};
virtual void SetName(string name){printf("DERIVED CLASS: in Set name \n");}
virtual float Evaluate(float time){printf("DERIVED CLASS: in Evaluate\n");return 1.0;}
virtual bool DataExists(){printf("DERIVED CLASS:in data exists\n");return true;}
virtual void MyFunction(){printf("DERIVED CLASS: in my function\n");}
virtual void SetObject(BaseClass *input){printf("DERIVED CLASS: in set object\n");}
};
#endif /* defined(__DerivedClass__) */
inheritTest.pyx:
#ifndef __NextDerivedClass__
#define __NextDerivedClass__
#include "DerivedClass.h"
class NextDerivedClass:public DerivedClass
{
public:
NextDerivedClass(){};
virtual ~NextDerivedClass(){};
virtual void SetObject(BaseClass *input){printf("NEXT DERIVED CLASS: in set object\n");}
virtual bool DataExists(){printf("NEXT DERIVED CLASS: in data exists \n");return true;}
};
#endif /* defined(__NextDerivedClass__) */
test.py:
#Necessary Compilation Options
#distutils: language = c++
#distutils: extra_compile_args = ["-std=c++11", "-g"]
#Import necessary modules
from libcpp cimport bool
from libcpp.string cimport string
from libcpp.map cimport map
from libcpp.pair cimport pair
from libcpp.vector cimport vector
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()
void SetObject(BaseClass *)
cdef extern from "NextDerivedClass.h":
cdef cppclass NextDerivedClass(DerivedClass):
NextDerivedClass() except +
cdef class PyBaseClass:
cdef BaseClass *thisptr
def __cinit__(self):
if type(self) is PyBaseClass:
self.thisptr = new BaseClass()
def __dealloc__(self):
if type(self) is PyBaseClass:
del self.thisptr
def SetName(self, name):
self.thisptr.SetName(name)
def Evaluate(self, time):
return self.thisptr.Evaluate(time)
def DataExists(self):
return self.thisptr.DataExists()
cdef class PyDerivedClass(PyBaseClass):
cdef DerivedClass *derivedptr
def __cinit__(self):
if type(self) is PyDerivedClass:
self.derivedptr = self.thisptr = new DerivedClass()
def __dealloc__(self):
if type(self) is PyBaseClass:
del self.derivedptr
def SetObject(self, PyBaseClass inputObject):
self.derivedptr.SetObject(<BaseClass *>inputObject.thisptr)
def MyFunction(self):
self.derivedptr.MyFunction()
cdef class PyNextDerivedClass(PyDerivedClass):
cdef NextDerivedClass *nextDerivedptr
def __cinit__(self):
self.nextDerivedptr = self.derivedptr = self.thisptr = new NextDerivedClass()
def __dealloc__(self):
del self.nextDerivedptr
请注意我打电话时:
from inheritTest import PyBaseClass as base
from inheritTest import PyDerivedClass as der
from inheritTest import PyNextDerivedClass as nextDer
a = der()
b = der()
a.SetObject(b)
c = nextDer()
a.SetObject(c)
c.DataExists()
c.SetObject(b)
c.Evaluate(0.3)
baseSig = base()
signal = der()
baseSig.SetName('test')
signal.SetName('testingone')
baseSig.Evaluate(0.3)
signal.Evaluate(0.5)
signal.SetObject(b)
baseSig.DataExists()
signal.DataExists()
它的工作方式是Cython沿着继承树去寻找
&#34;最新&#34;评估的实施。如果它存在于c = nextDer()
c.Evaluate(0.3)
中,它会调用它(我已经尝试过并且它有效),因为它不在那里,它会向上一步并检查NextDerivedClass.h
。该函数在那里实现,因此输出为:
DerivedClass
我希望这对未来的某个人有帮助,如果我的理解或语法/语法有错误,请随时在下面发表评论,我会尝试解决它们。再次,非常感谢那些在下面回答的人,这是对他们答案的总结,只是为了帮助验证我的理解。谢谢!
答案 1 :(得分:1)
您编写的代码无法编译。我怀疑你的真实PyDerivedClass
并非真正来自PyBaseClass
,好像它最后一行必须是
(<DerivedClass*>self.thisptr).SetObject(inputObject.thisptr)
这也可以解释你得到的类型错误,这是我无法重现的错误。
答案 2 :(得分:0)
老实说,这看起来像个错误。您传入的对象是所需类的实例,但仍会引发错误。您可能希望在cython-users邮件列表中提出它,以便主要开发人员可以查看它。
一种可能的解决方法是定义一个代表两种类型参数的fused type并在方法中使用它。这看起来有点矫枉过正。