python - 在 Cython 中包装自定义类型 C++ 指针

标签 python c++ pointers numpy cython

使用 Cython 包装自定义类型 C++ 指针的最佳方法是什么?

例如:

import numpy as np
cimport numpy as np

cdef extern from "A_c.h"
    cdef cppclass A:
       A();
       void Foo(A* vec);

cdef class pyA:
    cdef A *thisptr
    def ___cinit___(self):
        self.thisptr = new A()
    def __dealloc___(self):
        del self.thisptr

我应该如何使用cython来包装Foo?我已经尝试了以下但我从 Buffer.py 中得到了断言错误或者 A 不是内存 View 切片的基本类型的错误

def Foo(self, np.ndarray[A, mode='c'] vec)
def Foo(self, A[::1] vec)   

最佳答案

基本上每次你想传递一个A类型的对象或一个指向它的指针时,你应该使用一个pyA类型的Python对象——这实际上非常类似于一个指针,除了它有引用计数,所以它就像一个 shared_ptr在 C++11 中,只是它只知道 Python(或 Cython)中的引用。 [编辑] 请注意,Python 对象可以是 None,您可以使用 not None 子句轻松防止这种情况。

当然这不仅适用于参数而且适用于返回类型,因此每个返回指向类型 A 的对象的指针的方法都应该返回一个 pyA-对象代替。为此,您可以创建一个 cdef 方法名称,例如 setThis,它允许设置包含的指针。

如上所述,如果您以这种方式包装指针,内存管理是在 Python 中完成的,因此一方面您需要确保如果您的 C++ 对象持有指向某个对象的指针,则该 Python 对象不会被删除(例如,通过在 Cython 中存储对 Python 对象的引用),另一方面,如果对象仍包含在 Python 对象中,则不应从 C++ 中删除对象。如果您已经在 C++ 中进行了某种内存管理,您还可以向您的 Cython 对象添加标志是否应删除 C++ 对象。

我对您的示例进行了一些扩展,以说明如何在 Cython 中实现这一点:

cdef extern from "A_c.h":
    cdef cppclass A:
        A()
        void Foo(A* vec)
        A* Bar()

    cdef cppclass AContainer:
        AContainer(A* element)

cdef class pyA:
    cdef A *thisptr
    def ___cinit___(self):
        self.thisptr = new A()

    def __dealloc___(self):
        del self.thisptr

    cdef setThis(self, A* other):
        del self.thisptr
        self.thisptr = other
        return self

    def Foo(self, pyA vec not None): # Prevent passing None
        self.thisptr.Foo(vec.thisptr)

    def Bar(self):
        return pyA().setThis(self.thisptr.Bar())

cdef class pyAContainer:
    cdef AContainer *thisptr
    cdef pyA element

    def __cinit__(self, pyA element not None):
        self.element = element # store reference in order to prevent deletion
        self.thisptr = new AContainer(element.thisptr)

    def __dealloc__(self):
        del self.thisptr # this should not delete the element
        # reference counting for the element is done automatically

关于python - 在 Cython 中包装自定义类型 C++ 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770963/

相关文章:

python - 清除元类单例

python - 运行Web2py后如何添加SSL证书 'one step production deployment'

python - pyvista 射线追踪仅检测到一个交叉点

c++ - C++ 中以 Listclass-parent 作为成员的 Itemclass

c - 如何释放指向指针的指针,以便释放其中的所有元素?

C++ 遍历成员函数

python - 断言两帧不相等

c++ - Xcode shell脚本调用错误

c++ - boost 是否提供 make_zip_range?

c - 了解指针在嵌入式系统中的使用