太好了!
虽然不完整但足够使用。我已经能够为自己的目的做到这一点。结合上面链接的来源和这篇文章,这并不容易,因为我是Cython的初学者,但我确认这是我在www上找到的唯一方法。
非常感谢你们。
很抱歉我没有太多时间进入文本细节,但这里是我的文件(可能有助于获得另一个将所有这些内容组合在一起的视角)
setup.py :
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [
Extension("elps",
sources=["elps.pyx", "src/ITestClass.cpp"],
libraries=["elp"],
language="c++",
)
]
)
TestClass :
#ifndef TESTCLASS_H_
#define TESTCLASS_H_
namespace elps {
class TestClass {
public:
TestClass(){};
virtual ~TestClass(){};
int getA() { return this->a; };
virtual int override_me() { return 2; };
int calculate(int a) { return a * this->override_me(); }
private:
int a;
};
}
#endif
ITestClass.h:
#ifndef ITESTCLASS_H_
#define ITESTCLASS_H_
#include "../elps_api.h"
#include "../../inc/TestClass.h"
namespace elps {
class ITestClass : public TestClass {
public:
PyObject *m_obj;
ITestClass(PyObject *obj);
virtual ~ITestClass();
virtual int override_me();
};
}
#endif
ITestClass.cpp :
#include "ITestClass.h"
namespace elps {
ITestClass::ITestClass(PyObject *obj): m_obj(obj) {
if (import_elps()) {
} else {
Py_XINCREF(this->m_obj);
}
}
ITestClass::~ITestClass() {
Py_XDECREF(this->m_obj);
}
int ITestClass::override_me()
{
if (this->m_obj) {
int error;
int result = cy_call_func(this->m_obj, (char*)"override_me", &error);
if (error)
result = TestClass::override_me();
return result;
}
return 0;
}
}
编辑2:关于纯虚方法的说明(似乎是一个相当经常出现的问题)。如上所示,以这种特定方式,“TestClass :: override_me()”不能是纯虚的,因为如果在Python的扩展类中没有重写该方法,则必须能够调用它(即:不落入“错误”/“未找到覆盖”部分的“ITestClass :: override_me()”体中)。
扩展:elps.pyx:
cimport cpython.ref as cpy_ref
cdef extern from "src/ITestClass.h" namespace "elps" :
cdef cppclass ITestClass:
ITestClass(cpy_ref.PyObject *obj)
int getA()
int override_me()
int calculate(int a)
cdef class PyTestClass:
cdef ITestClass* thisptr
def __cinit__(self):
self.thisptr = new ITestClass(<cpy_ref.PyObject*>self)
def __dealloc__(self):
if self.thisptr:
del self.thisptr
def getA(self):
return self.thisptr.getA()
cpdef int calculate(self, int a):
return self.thisptr.calculate(a) ;
cdef public api int cy_call_func(object self, char* method, int *error):
try:
func = getattr(self, method);
except AttributeError:
error[0] = 1
else:
error[0] = 0
return func()
最后,Python 调用:
from elps import PyTestClass as TC;
a = TC();
print a.calculate(1);
class B(TC):
def override_me(self):
return 5
b = B()
print b.calculate(1)
这应该能让前面链接的工作更加直接地与我们正在讨论的问题相关。另一方面,上述代码可以通过使用“hasattr”而不是try/catch块进行优化:
cdef public api int cy_call_func_int_fast(object self, char* method, bint *error):
if (hasattr(self, method)):
error[0] = 0
return getattr(self, method)();
else:
error[0] = 1
当然,上述代码只有在我们不覆盖“override_me”方法的情况下才会有所区别。