一种将c ++对象传递给cython中另一个对象的方法的方法

时间:2016-09-01 21:13:48

标签: python c++ cython

我有两个课程(让我们假设最简单的课程,实施并不重要)。我的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中的另一个方法?

1 个答案:

答案 0 :(得分:1)

def func(self, A a):
    return # ... as before

您需要告诉Cython a类型为A(调用时会检查类型)。这样它就知道a._this并且不将其视为Python属性查找。如果Cython在完成时知道类型,则只能访问cdef ed属性。