【发布时间】:2017-09-21 11:38:00
【问题描述】:
我正在尝试用 Cython 包装一些 c++ 类。对于基类,一切正常。对于具有相同参数(在其构造函数中)与其各自基类的参数的派生类,也会发生同样的情况。但是,我无法实例化具有与其基类不同数量的参数(在其构造函数中)的派生类。
例如:
- h 文件
// CYH.h file
#ifndef __CYH_H__
#define __CYH_H__
#include <iostream>
class Base
{
public:
Base(double);
~Base();
double A;
double getA();
void setA(double);
};
class Derived : public Base
{
public:
Derived(double, double);
~Derived();
double B;
};
#endif
- cpp 文件
// cyh.cpp file
#include <iostream>
#include <string>
#include "include/cyh.h"
Base::Base(double a)
{
A = a;
}
Base::~Base()
{
}
double Base::getA(){
return A;
}
void Base::setA(double a_){
A = a_;
}
Derived::Derived(double a, double b) : Base(a)
{
B = b;
}
Derived::~Derived()
{
}
- 和 pyx 文件
cdef extern from "include/cyh.h":
cdef cppclass Base:
Base(double)
double getA()
void setA(double)
cdef cppclass Derived(Base):
Derived(double, double)
cdef class cyBase:
cdef Base *thisptr
def __cinit__(self, double a):
if type(self) is cyBase:
self.thisptr = new Base(a)
def __dealloc__(self):
if type(self) is cyBase:
del self.thisptr
@property
def A(self):
return self.thisptr.getA()
@A.setter
def A(self, value):
self.thisptr.setA(value)
cdef class cyDerived(cyBase):
cdef Derived *thisptrDerived
def __cinit__(self, double a, double b):
if type(self) is cyDerived:
self.thisptrDerived = self.thisptr = new Derived(a, b)
def __dealloc__(self):
if type(self) is cyDerived:
del self.thisptrDerived
它编译并且 pyd 构建成功。但是,当我尝试使用以下方法实例化 cyDerived 类时:
mycyObj = cyDerived(a=2., b=3.)
我收到以下错误:
__cinit__() got an unexpected keyword argument 'b'
蚂蚁知道我做错了什么?
非常感谢!
【问题讨论】:
-
这可能解决了你的问题:stackoverflow.com/a/33091422/5769463
-
非常感谢您的评论和链接。我在groups.google.com/forum/#!topic/cython-users/N-jXUWLzd6o 指出的基类中使用了 *args 和 **kwards。但是,据说这可能会带来效率损失(我不明白为什么)。我想知道是否有更有效的方法。
-
一种选择是在基类构造函数中“预期”
b并在那里忽略它 - 但这会使代码不那么干净,所以我只会这样做stackoverflow.com/a/13811280/5769463 -
我使用了 *args 和 **kwards。为什么这会影响性能?在哪里?在类实例化期间?
标签: python c++ inheritance cython