python - Cython:复制构造函数

标签 python cython

我有以下 C++ 类接口(interface),我正在尝试对其进行 cythonize。

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

最佳答案

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

关于python - Cython:复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37262974/

相关文章:

python - Pandas:子索引数据框:副本与 View

python - Cython 函数比纯 python 花费更多时间

enums - 在 cython 中包装 typedefed 枚举

python - 赛通 "Cannot take address of memoryview slice"

python - 使用Cython加速连通分量算法

python - 将 dash 应用程序布局输入框与下拉列表和日期对齐

python - 关闭服务器后尝试运行服务器时,Django python已停止工作

python - 使用 QWebView 请求的 POST 请求

python - 如何创建空词典列表并填充后记?

python - Cython setup.py 找不到已安装的 Visual C++ 构建工具