2016-09-01 174 views
1

我有两个类(让我们假设最简单的,实现并不重要)。我defs.pxd文件(用Cython DEFS)看起来是这样的:一种将C++对象传递给另一个对象的方法的方法

cdef extern from "A.hpp": 
    cdef cppclass A: 
    A() except + 

cdef extern from "B.hpp": 
    cdef cppclass B: 
    B() except + 
    int func (A) 

pyx文件(蟒蛇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)没有按” t带有此错误:

Invalid operand type for '*' (Python object) 

如何将一个python对象的内部C++对象传递给另一个方法在python中?

回答

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

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

相关问题