Наследование Cython и C++

У меня есть 2 класса, A и B. B наследуется от A.

//C++    
class A
{
    public:
        int getA() {return this->a;};
        A() {this->a = 42;}
    private:
        int a;

};

class B: public A
{
    public:
       B() {this->b = 111;};
       int getB() {return this->b;};
    private:
        int b;

};

Теперь я хотел бы связать эти два класса с помощью Cython и иметь возможность вызывать getA ()из экземпляра B:

a = PyA()
b = PyB()
assert a.getA() == b.getA()

В настоящее время мой файл pyx выглядит так:

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 = <A*>0

    def getB(self):
       return (<B*>self.thisptr).getB()

Хотя я надеюсь, что этот код не делает ничего слишком опасного, я также надеюсь, что есть лучший способ справиться с этим.

Кроме того, использование модуля приводит к следующему результату.:

>>> from inherit import *
>>> b = PyB()
in A: allocating thisptr
in B: deallocating old A
in B: creating new b
>>> b.getA()
42
>>> b.getB()
111
>>> del b
in B: deallocating thisptr

И мне не очень нравится выделять экземпляр A только для того, чтобы освободить его сразу после этого.

Посоветуйте, как это сделать правильно?

13
задан ascobol 9 May 2012 в 15:58
поделиться