gpt4 book ai didi

python - Cython/Python/C++ - 继承 : Passing Derived Class as Argument to Function expecting base class

转载 作者:太空狗 更新时间:2023-10-29 20:12:25 25 4
gpt4 key购买 nike

我正在使用 Cython 包装一组 C++ 类,允许它们使用 Python 接口(interface)。示例代码如下:

基类.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__) */

派生类.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__) */

继承测试.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,如下所示:

主要.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 *

对此的一种 hacky 解决方法只是让 Python 函数具有不同的名称,期望不同类型的参数(例如:SetObjectWithBase、SetObjectWithDerived),然后在它们的实现中,只需调用具有类型的相同的基于 C 的函数-转换输入。我知道这是可行的,但我想尽可能避免这样做。即使有一种方法可以在函数中捕获类型错误,并在内部处理它,我认为这可能有效,但我不确定具体如何实现它。

希望这个问题有意义,如果您需要更多信息,请告诉我。

****编辑****:代码已经过编辑,基本继承有效。多玩了一会儿之后,我意识到问题出在多级继承上,例如,请参阅上面的编辑代码。基本上,为 NextDerivedClass 保留 SetObject 的声明会导致“歧义重载方法”错误,不保留它允许我调用对象上的函数,但它会调用继承的实现(来自 DerivedClass)。 **

最佳答案

在得到以下答案和实验的大量帮助后,我想我明白了在 Cython 中实现基本继承是如何工作的,我正在回答我自己的问题以验证/提高我的理解,并希望能帮助任何人以后可能会遇到相关的问题。如果这个解释有什么不对的地方,欢迎在下方评论中指正,我会进行编辑。我不认为这是唯一的方法,所以我确信替代方法有效,但这是对我有用的方法。

概述/学到的东西:

所以基本上,根据我的理解,Cython 足够聪明(给定适当的信息)遍历继承层次结构/树并根据您调用它的对象的类型调用适当的虚函数实现.

重要的是尝试并反射(reflect)您试图包装在 .pyx 文件中的 C++ 继承结构。这意味着确保:

1) 导入的 C++/Cython cpp 类(声明为 cdef extern from 的类)以与实际 C++ 类相同的方式相互继承

2) 只为每个导入类声明唯一的方法/成员变量(对于实现的虚函数,不应同时为 BaseClassDerivedClass 声明函数两类不同)。只要一个继承另一个,函数声明只需要在Base导入类中。

3) Python 包装类(即 PyBaseClass/PyDerivedClass)也应该像实际的 C++ 类一样相互继承

4) 与上面类似,虚函数的接口(interface)只需要存在于PyBase 包装类中(不应同时放入两个类中,实际运行时将调用正确的实现代码)。

5) 对于每个子类化或继承自的 Python 包装类,您需要一个 if type(self) is class-name: 检查 __cinit__()__dealloc__() 函数。这将防止段错误等。您不需要检查层次树中的“叶节点”(不会继承或子类化的类)

6) 确保在 __dealloc__() 函数中,您只删除当前指针(而不是任何继承的指针)

7) 同样,在 __cinit__() 中,对于继承的类,请确保设置当前指针,以及指向您尝试创建的类型的对象的所有派生指针(即. *self.nextDerivedptr = self.derivedptr = self.thisptr = new NextDerivedClass()*)

希望当您看到下面的代码时,上面的观点能理解很多,它会编译和运行/工作,因为我需要/希望它工作。

基类.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__) */

派生类.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__) */

NextDerivedClass.h:

    #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__) */

继承测试.pyx:

#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

测试.py:

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()

请注意,当我调用时:

c = nextDer()
c.Evaluate(0.3)

它的工作方式是 Cython 沿着继承树向下寻找评估的“最新”实现。如果它存在于 NextDerivedClass.h 中,它会调用它(我已经尝试过并且它有效),但是由于它不存在,它会更上一层楼并检查 DerivedClass .该函数在那里实现,因此输出为:

>> DERIVED CLASS: in Evaluate

我希望这对以后的人有所帮助,如果我的理解有错误或只是语法/语法错误,请随时在下面发表评论,我会尝试解决这些问题。再次感谢那些在下面回答的人,这是他们回答的总结,只是为了帮助验证我的理解。谢谢!

关于python - Cython/Python/C++ - 继承 : Passing Derived Class as Argument to Function expecting base class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com