簡體   English   中英

在Cython中包裝自定義類型C ++指針

[英]Wrapping custom type C++ pointer in 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不是memoryview切片的基本類型的錯誤

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

基本上每次要傳遞A類型的對象或指向它的指針時,都應該使用pyA類型的Python對象 - 除了它有引用計數之外,它實際上非常類似於指針,所以它就像一個C ++ 11中的shared_ptr ,只是它只知道Python(或Cython)中的引用。 [編輯]請注意,Python對象可以是None ,您可以使用not None子句輕松防止這種情況。

當然,這不僅適用於參數,也適用於返回類型,因此返回指向類型A的對象的指針的每個方法都應返回pyA 為此,您可以創建一個cdef方法名稱,例如setThis ,它允許設置包含的指針。

如上所述,內存管理是在Python中完成的,如果你用這種方式包裝指針,那么一方面你需要確保如果你的C ++對象擁有一個指向一個對象的指針,而Python對象沒有被刪除(例如通過存儲一個引用)到Cython中的Python對象)另一方面,如果它們仍然包含在Python對象中,則不應該從C ++中刪除對象。 如果在C ++中已經有某種內存管理,如果要刪除C ++對象,你也可以為你的Cython對象添加標志。

我已經擴展了你的例子,以說明如何在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM