Hello,
I'm wrapping with Cython a vast C++ project where a large number of
classes inherit from a limited number of base classes. To avoid
repeating myself too much I would like to exposed the interface
described by the base classes using class inheritance in Cython as well.
However I haven't found a way to do that that does not requires some
ugly explicit type casting.
A simple example. Given the C++ class definitions:
class Base {
private:
std::string _name;
public:
Base(std::string n) : _name(n) { };
std::string name() { return _name; };
};
class Example : public Base {
public:
Example(std::string n) : Base(n) { };
int foo(int a, int b) { return (a + b); };
};
I can write the following Cython:
cdef extern from "example.h":
cppclass _Base "Base":
_Base(string n)
string name()
cppclass _Example "Example":
_Example(string n)
string name()
int foo(int a, int b)
cdef class Base:
cdef _Base *obj
def __cinit__(self, n):
self.obj = new _Base(n)
def name(self):
return
self.obj.name()
cdef class Example:
cdef _Example *obj
def __cinit__(self, name):
self.obj = new _Example(name)
def name(self):
return
self.obj.name()
def foo(self, a, b):
return self.obj.foo(a, b)
What I would like to do is to avoid to have to repeat the declaration of
the inherited methods. My solution is the following:
from libcpp.string cimport string
cdef extern from "example.h":
cppclass _Base "Base":
_Base(string n)
string name()
cppclass _Example "Example":
_Example(string n)
int foo(int a, int b)
cdef class Base:
cdef _Base *obj
def __cinit__(self, n):
self.obj = new _Base(n)
def name(self):
return
self.obj.name()
cdef class Example(Base):
def __cinit__(self, name):
self.obj = <_Base *>(new _Example(name))
def foo(self, a, b):
return (<_Example *>self.obj).foo(a, b)
which works fine (as for as I can tell), but the explicit type castings
really look ugly. I don't have much C++ or Cython experience, there is a
better way of doing what I'm trying to do?
Thank you!
Cheers,
Daniele