Cython: Casting vector of C++ `std::complex<double>` to C `double complex`

244 Views Asked by At

In Cython, starting from a C++ vector of std::complex<double> like this...

# Imports 
from libcpp.vector cimport vector
from libcpp.complex cimport complex as cpp_complex
ctypedef my_complex = cpp_complex[double]

# Code
cdef vector[my_complex] vec

... how can I convert this vector to a double complex memoryview with the default cython/python's complex?

cdef complex[::1] mem_view = ???

Alternatively, how can I tell Cython to use C++'s std::complex<double> instead of double complex as the underneath type of complex?

1

There are 1 best solutions below

4
ibarrond On

It suffices to extract a pointer to the data with vec.data() (returns a complex[double]*), cast it to cython complex*, and cast the array to the fixed vector size:

cdef complex[::1] mem_view = <complex[:vec.size()]>(<complex*>vec.data())

For the alternative (setting std::complex<double> | cython's cpp_complex[double] to be the standard complex type), one would have to add some defines to trigger the choice in https://github.com/cython/cython/blob/master/Cython/Utility/Complex.c#L56. However, I'm not sure how to do that.