Specify C++ template type in Python

118 views
Skip to first unread message

csd

unread,
Mar 23, 2012, 7:44:15 AM3/23/12
to cython-users
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

Robert Bradshaw

unread,
Mar 23, 2012, 5:07:59 PM3/23/12
to cython...@googlegroups.com

No, this isn't (currently) possible. The issue is that the C++
template type needs to be determined at compile time, but you're
trying to defer the decision to runtime. Compiling several different
specializations is the only way to do it.

You may also want to take a look at fused types (though this is not
yet supported for classes).

- Robert

Reply all
Reply to author
Forward
0 new messages