【发布时间】:2012-10-23 12:07:06
【问题描述】:
我对 Cython 使用默认构造函数有疑问。
我的C++类Node如下
Node.h
class Node
{
public:
Node()
{
std::cerr << "calling no arg constructor" << std::endl;
w=0.0;
d=0.0;
}
Node(double val, double val2);
{
std::cerr << "calling 2 args constructor" << std::endl;
this->w=val;
this->d=val2;
}
private:
double d,w;
}
如下包裹在 Cython 中
cdef extern from "Node.h":
cdef cppclass Node:
Node() except +
Node(double val1, double val2) except +
double d
double w
cdef class pyNode:
cdef Node *thisptr # hold a C++ instance which we're wrapping
def __cinit__(self):
self.thisptr = new Node()
def __cinit__(self, double val1, double val2):
self.thisptr = new Node(val1,val2)
def __dealloc__(self):
del self.thisptr
def __repr__(self):
return "d=%s w=%s" % (self.thisptr.w, self.thisptr.w )
Cython 代码编译良好,尤其是从 Python 调用时
from pyNode import pyNode as Node
n=Node(1.0,2.0)
我得到了预期的calling 2 args constructor 字符串,但是如果我尝试使用“无参数”构造函数从 python 声明一个 Node 对象(应该正确声明为__cinit__(self),我没有得到任何输出,这意味着没有调用无参数构造函数!
如何从包装类的 cinit 方法中显式调用它?
【问题讨论】:
标签: c++ python constructor cython default-constructor