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?
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]
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With