A way to pass c++ object to another object's method in cython
<p>I have two classes (let's assume the most simple ones, implementation is not important). My <code>defs.pxd</code> file (with cython defs) looks like this:</p>

<pre><code>cdef extern from "A.hpp":
  cdef cppclass A:
    A() except +

cdef extern from "B.hpp":
  cdef cppclass B:
    B() except +
    int func (A)
</code></pre>

<p>My <code>pyx</code> file (with python defs) looks like this:</p>

<pre><code>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))
</code></pre>

<p>The thing is that <code>deref(self._this)</code> works right, but <code>deref(a._this)</code> doesn't with this error:</p>

<pre><code>Invalid operand type for '*' (Python object)
</code></pre>

<p>How can I pass one python object's internal c++ object to another one's method in python?</p>

<pre><code>def func(self, A a):
    return # ... as before
</code></pre>

<p>You need to tell Cython that <code>a</code> is of type <code>A</code> (the type is checked when you call it). That way it knows about <code>a._this</code> and doesn't treat it as a Python attribute lookup. You can only access <code>cdef</code>ed attributes if Cython knows the type at comple time.</p>

python c++ cython