Python 来自 cython 中 C++ 对象的组件生成器

Python component builder from C++ objects in cython

我正在尝试寻找如何在 cython 中使用 C++ 对象制作 python builder。我尝试在等效示例中总结代码。 (我找不到如何使用 __init__() 和 __cinit__() 来提供指针和 C 变量,我正在使用 setter/getter bypass .)

cdef extern from "device.h":
    cdef cppclass CDevice

cdef class PyDevice:
    cdef CDevice* _cdevice
    #(...)
    cdef SetDevice(CDevice* cdevice):
        self._cdevice = cdevice
    #(...)

cdef extern from "component.h":
    cdef cppclass CComponent

cdef class PyComponent:
    cdef CComponent _ccomponent
    #(...)
    cdef CComponent GetComponent(self):
        return self._ccomponent
    #(...)

cdef extern from "builder.h":
    cdef cppclass CBuilder:
        CDevice* BuildDevice(CComponent&) except+

cdef class PyBuilder:
    cdef CBuilder* _cbuilder
    #(...)
    def BuildDevice(self,pyComponent):
        pydevice = PyDevice()
        pydevice.SetDevice(self._cbuilder.BuildDevice(pyComponent.GetComponent()))
    #(...)

我可以从编译错误中看到的问题是,从 "GetComponent()" 返回似乎变成了 Python 对象而不是 "Component" 对象。可以看看哪里出错的细节吗?

改变

def BuildDevice(self,pyComponent):

def BuildDevice(self,PyComponent pyComponent):

因为它不知道您传递的参数类型(在编译时),所以它无法判断调用 pyComponent.GetComponent() 应该调用 cdef 函数,因此它不知道它 returns C 对象。