我有两个课程(让我们假设最简单的课程,实施并不重要)。我的defs.pxd
文件(使用cython defs)看起来像这样:
cdef extern from "A.hpp":
cdef cppclass A:
A() except +
cdef extern from "B.hpp":
cdef cppclass B:
B() except +
int func (A)
我的pyx
文件(使用python defs)如下所示:
from cython.operator cimport dereference as deref
from libcpp.memory cimport shared_ptr
cimport defs
cdef class A:
cdef shared_ptr[cquacker_defs.A] _this
@staticmethod
cdef inline A _from_this(shared_ptr[cquacker_defs.A] _this):
cdef A result = A.__new__(A)
result._this = _this
return result
def __init__(self):
self._this.reset(new cquacker_defs.A())
cdef class B:
cdef shared_ptr[cquacker_defs.B] _this
@staticmethod
cdef inline B _from_this(shared_ptr[cquacker_defs.B] _this):
cdef B result = B.__new__(B)
result._this = _this
return result
def __init__(self):
self._this.reset(new cquacker_defs.B())
def func(self, a):
return deref(self._this).func(deref(a._this))
问题是deref(self._this)
正常,但deref(a._this)
没有解决此错误:
Invalid operand type for '*' (Python object)
如何将一个python对象的内部c ++对象传递给python中的另一个方法?
答案 0 :(得分:1)
def func(self, A a):
return # ... as before
您需要告诉Cython a
类型为A
(调用时会检查类型)。这样它就知道a._this
并且不将其视为Python属性查找。如果Cython在完成时知道类型,则只能访问cdef
ed属性。