2016-05-16 159 views
1

我有以下C++类接口,我试图cythonize。Cython:复制构造函数

class NetInfo 
{ 
public: 
    NetInfo(); 
    NetInfo(NetInfo const& rhs); 
    virtual ~NetInfo(); 
    void swap(NetInfo& rhs) throw(); 
    NetInfo& operator=(NetInfo rhs); 
    ... 
} 

这是我到目前为止。我不完全确定如何实现复制构造函数。我在Cython用户指南中没有看到任何示例。复制构造中的问题是如何从'other'(一个PyNetInfo对象)获取NetInfo对象。有任何想法吗?

cdef extern from 'NetInfo.h' namespace '...': 
    cdef cppclass NetInfo: 
     NetInfo() except + 
     NetInfo(NetInfo&) except + 
     operator=(NetInfo) except + 
     ... 

cdef class PyNetInfo: 
    cdef NetInfo* thisptr 

def __cinit__(self, PyNetInfo other=None): 
    cdef PyNetInfo ostr 
    if other and type(other) is PyNetInfo: 
     ostr = <PyNetInfo> other 
     self.thisptr = ostr.thisptr 
    else: 
     self.thisptr = new NetInfo() 
    def __dealloc__(self): 
     del self.thisptr 

回答

2

用Cython具有特殊的运营商处理C++的*,&,++, - 是用Python语法兼容。因此,他们需要被引用和使用。见http://cython.org/docs/0.24/src/userguide/wrapping_CPlusPlus.html#c-operators-not-compatible-with-python-syntax

from cython.operator cimport dereference as deref 

cdef class PyNetInfo: 
    cdef NetInfo* thisptr 

    def __cinit__(self, other=None): 
     cdef PyNetInfo ostr 
     if other and type(other) is PyNetInfo: 
      ostr = <PyNetInfo> other 
      self.thisptr = new NetInfo(deref(ostr.thisptr)) 
     else: 
      self.thisptr = new NetInfo() 
    def __dealloc__(self): 
     del self.thisptr 

这里是输出:

Type "help", "copyright", "credits" or "license" for more information. 
>>> import netinfo 
>>> a = netinfo.PyNetInfo() 
>>> b = netinfo.PyNetInfo() 
>>> a.setNetName('i am a') 
>>> b.setNetName('i am b') 
>>> c = netinfo.PyNetInfo(b) <-- copy construction. 
>>> a.getNetName() 
'i am a' 
>>> b.getNetName() 
'i am b' 
>>> c.getNetName()  <--- c == b 
'i am b' 
>>> c.setNetName('i am c') <-- c is updated 
>>> a.getNetName() 
'i am a' 
>>> b.getNetName()  <-- b is not changed 
'i am b' 
>>> c.getNetName()  <-- c is changed 
'i am c' 
>>> exit()