I wanted to wrap some C++ code using Cython (to be callable in Python)
and wondered if one could specify the template type in Python itself
somehow. To illustrate the problem, consider the code which wraps the C
++ vector class in Cython (taken from
http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html
)
from cython.operator cimport dereference as deref, preincrement as inc
#dereference and increment operators
cdef extern from "<vector>" namespace "std":
cdef cppclass vector[T]:
cppclass iterator:
T operator*()
iterator operator++()
bint operator==(iterator)
bint operator!=(iterator)
vector()
void push_back(T&)
T& operator[](int)
T& at(int)
iterator begin()
iterator end()
Ideally I would like to make this code callable from Python using
something like:
a = PyVector(int)
where int becomes the template type.
My incorrect attempt so far looks like this:
cdef class PyVector:
cdef vector[T] *thisptr # hold a C++ instance which we're
wrapping
def __cinit__(self, tempType):
self.thisptr = new vector[tempType]()
but I need to specify the template type of the instance variable
before the constructor. One way to get around it is to hard-code
several types in different classes, and then choose one in the
constructor of PyVector, but this isn't ideal. Any ideas?
Thanks for you help,
Charanpal