2016-05-16 6 views
1

私はcythonizeしようとしている次のC++クラスのインターフェイスを持っています。Cython:コピーコンストラクタ

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

これまで私がこれまで行ってきたことです。コピーコンストラクタを実装する方法は完全にはわかりません。私はCythonユーザーガイドで例を見ていません。コピー構築の問題は、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の構文と互換性があります。したがって、彼らは持ち帰りして使用する必要があります。参照してくださいここで

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 

http://cython.org/docs/0.24/src/userguide/wrapping_CPlusPlus.html#c-operators-not-compatible-with-python-syntaxが出力されます。

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()