Search code examples
c++fftwcomplex-numbersreinterpret-cast

Problem casting STL complex<double> to fftw_complex


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?


Solution

  • Re-write your code as follows:

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

    Every compiler I've used will optimise out the memcpy because it is copying a fixed, ie at compile time, amount of data.

    This avoids pointer aliasing issues.

    Edit: You can also avoid strict aliasing issues using a union as follows:

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

    Though strictly this C99 rules (Not sure about C++) are broken as reading from a different member of a union to the one written too is undefined. It works on most compilers though. Personally I prefer my original method.