Passing C++ pointer as argument into Cython function

后端 未结 4 2225
萌比男神i
萌比男神i 2021-02-04 00:36
cdef extern from \"Foo.h\":
    cdef cppclass Bar:
        pass

cdef class PyClass:
    cdef Bar *bar

    def __cinit__(self, Bar *b)
        bar = b

4条回答
  •  忘掉有多难
    2021-02-04 01:26

    Python class accepts Python arguments. To pass a C++ argument you need to wrap it:

    # distutils: language = c++
    
    cdef extern from "Foo.h" namespace "baz":
        cdef cppclass Bar:
             Bar(double d)
             double get()
    
    cdef class PyBar: # wrap Bar class
        cdef Bar *thisptr
        def __cinit__(self, double d):
            self.thisptr = new Bar(d)
        def __dealloc__(self):
            del self.thisptr
        property d:
            def __get__(self):
                return self.thisptr.get()
    

    PyBar instances can be used as any other Python objects both from Cython and pure Python:

    class PyClass:
        def __init__(self, PyBar bar):
            self.bar = bar
    
    print(PyClass(PyBar(1)).bar.d)
    

提交回复
热议问题