Problem casting STL complex<double> to fftw_complex

galadog picture galadog · Nov 18, 2010 · Viewed 10k times · Source

The FFTW manual says that its fftw_complex type is bit compatible to std::complex<double> class in STL. But that doesn't work for me:

#include <complex>
#include <fftw3.h>
int main()
{
   std::complex<double> x(1,0);
   fftw_complex fx;
   fx = reinterpret_cast<fftw_complex>(x);
}

This gives me an error:

error: invalid cast from type ‘std::complex<double>’ to type ‘double [2]’

What am I doing wrong?

Answer

Bojan Nikolic picture Bojan Nikolic · Dec 2, 2012

The idea behind bit-compatibility of fftw_complex and C99 and C++ complex types is not that they can be easily created from one another, but that all functions in FFTW that take pointers to fftw_complex can also take pointers to c++ std::complex. Therefore the best approach is probably to use std::complex<> throughout your program and only convert pointers to these values when calling FFTW functions:

std::vector<std::complex<double> > a1, a2;
....
....
fftw_plan_dft(N, reinterpret_cast<fftw_complex*>(&a1[0]),
                 reinterpret_cast<fftw_complex*>(&a2[0]),
                 FFTW_FORWARD, FFTW_ESTIMATE);
....