相关疑难解决方法(0)

我可以使用Cython覆盖Python中的C++虚函数吗?

我有一个带有虚方法的C++类:

//C++
class A
{

    public:
        A() {};
        virtual int override_me(int a) {return 2*a;};
        int calculate(int a) { return this->override_me(a) ;}

};
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用Cython将此类暴露给Python,从Python继承此类并具有正确的重写:

#python:
class B(PyA):
   def override_me(self, a):
       return 5*a
b = B()
b.calculate(1)  # should return 5 instead of 2
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点 ?现在我想,如果我们可以在Cython中覆盖虚拟方法(在pyx文件中)也可能很棒,但允许用户在纯python中执行此操作更为重要.

编辑:如果这有帮助,解决方案可能是使用此处给出的伪代码:http://docs.cython.org/src/userguide/pyrex_differences.html#cpdef-functions

但是有两个问题:

  • 我不知道如何在Cython中编写这个伪代码
  • 也许有更好的方法

c++ python cython

12
推荐指数
2
解决办法
2869
查看次数

标签 统计

c++ ×1

cython ×1

python ×1