Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython C++ templates

I am fairly new to cython, and I was attempting to wrap a templated vector class defined as

template < typename T, uint N >   
struct Vector{}

and I am having a difficult time learning about how cython uses templates, especially those with an int as an argument. I read in the docs that ints are not yet supported as template parameters. How do I do this properly?

like image 454
Matt Ostlund Avatar asked Oct 29 '16 21:10

Matt Ostlund


2 Answers

For the curious, the Cython wiki shows how to write a templated class in Cython:

cdef extern from "<vector>" namespace "std":
    cdef cppclass vector[T]:
        ...

Furthermore, multiple template parameters are defined as a list. To answer the OP's question, one would use cdef struct Vector[T, N].

like image 92
colelemonz Avatar answered Sep 21 '22 04:09

colelemonz


I found an easy solution!

In a C++ header file, you can just declare a typedef, for example

typedef Vector<float,3>; Vector3f;

In your cython file you can just declare that and now you can use all the functions and operators within the class.

cdef extern from "Vector.h" namespace "ns":
    cdef cppclass Vector3f:

Now, I had an additional issue, and that is with "specialized" functions, in my case a specialization for a Vector with 3 params.

template<typename T1, typename T2>
inline Vector<T1, 3 >Cross(const Vector <T1, 3 > & v1, const Vector<T2, 3> & v2)

To use this in cython, just declare it outside the class, in my case

cdef extern from "Vector.h" namespace "ns":

    cdef cppclass Vector3f:

        ...

    Vector3f Cross(Vector3f v1,Vector3f v2)
like image 34
Matt Ostlund Avatar answered Sep 17 '22 04:09

Matt Ostlund