Note that there are some explanatory texts on larger screens.

plurals
  1. POCython and C++ inheritance
    primarykey
    data
    text
    <p>I have 2 classes, A and B. B inherits from A. </p> <pre class="lang-cpp prettyprint-override"><code>//C++ class A { public: int getA() {return this-&gt;a;}; A() {this-&gt;a = 42;} private: int a; }; class B: public A { public: B() {this-&gt;b = 111;}; int getB() {return this-&gt;b;}; private: int b; }; </code></pre> <p>Now I would like to interface those two classes using Cython and have the possibility to call the getA() method from a B instance:</p> <pre class="lang-python prettyprint-override"><code>a = PyA() b = PyB() assert a.getA() == b.getA() </code></pre> <p>Currently my pyx file looks like this:</p> <pre class="lang-cython prettyprint-override"><code>cdef extern from "Inherit.h" : cdef cppclass A: int getA() cdef cppclass B(A): int getB() cdef class PyA: cdef A* thisptr def __cinit__(self): print "in A: allocating thisptr" self.thisptr = new A() def __dealloc__(self): if self.thisptr: print "in A: deallocating thisptr" del self.thisptr def getA(self): return self.thisptr.getA() cdef class PyB(PyA): def __cinit__(self): if self.thisptr: print "in B: deallocating old A" del self.thisptr print "in B: creating new b" self.thisptr = new B() def __dealloc__(self): if self.thisptr: print "in B: deallocating thisptr" del self.thisptr self.thisptr = &lt;A*&gt;0 def getB(self): return (&lt;B*&gt;self.thisptr).getB() </code></pre> <p>While I hope this code is not doing anything too dangerous, I also hope there is a better way to handle it. </p> <p>Also using the module generates the following output:</p> <pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; from inherit import * &gt;&gt;&gt; b = PyB() in A: allocating thisptr in B: deallocating old A in B: creating new b &gt;&gt;&gt; b.getA() 42 &gt;&gt;&gt; b.getB() 111 &gt;&gt;&gt; del b in B: deallocating thisptr </code></pre> <p>And I don't really like allocating an A instance just to free it immediately after. </p> <p>Any advice about how to do it correctly ?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload