Problem casting STL complex to fftw_complex

前端 未结 3 1612
鱼传尺愫
鱼传尺愫 2020-12-28 08:25

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

<
3条回答
  •  佛祖请我去吃肉
    2020-12-28 08:54

    Re-write your code as follows:

    #include 
    #include 
    int main()
    {
       std::complex 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 
    #include 
    int main()
    {
       union stdfftw
       {
           std::complex< double > stdc;
           fftw_complex           fftw;
       };
       std::complex 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.

提交回复
热议问题