1

I am learning fftw (replace the self-defined fft function) in c++. In the old code, I have the algorithm designed in std::vector samples storage. According to the document, I use casting to interact the fftw datatype to my data (in std::vector).

#include <fftw3.h>
#include <vector>
#include <iostream>
#include <complex>

using namespace std;

void main(void)
{
  std::vector< complex<double> > x(4);
  x[0] = std::complex<double>(0.0, 0.0);
  x[1] = std::complex<double>(1.0, 0.0);
  x[2] = std::complex<double>(0.0, 2.0);
  x[3] = std::complex<double>(3.0, 3.0);

  // print the vector, looks good
  for (int i=0; i<4; i++)
  {
    cout << x[i] << endl;
  }    

  // refer fftw datatype to the std::vector by casting
  fftw_complex* in = reinterpret_cast<fftw_complex*>(&x[0]);

  // print in reference, gives random numbers
  for (int i=0; i<4; i++)
  {
    cout << *in[i*2] << " " << *in[i*2+1] << endl;
  }
}

But in seems not really pointing to the right place, it shows random numbers instead. Besides above question, my purpose is to generate a vector with 8 elements (example), the first 4 element refer to the std::vector but the last four is initialized as some constant. Is that possible to have *in pointing to the first in vector and then pointing to 4 constant values somewhere else, so I can fftw "in"? Thanks.

4

2 回答 2

2

http://www.fftw.org/fftw3_doc/Complex-numbers.html#Complex-numbers中所述,您必须使用 reinterpret_cast 从 double 转换为 fftw_complex。我想这是建议使用的少数情况之一。

它也说 fftw_complex 被定义为:

typedef double fftw_complex[2];

因此,横向循环的正确方法是执行以下操作:

for (int i=0; i<4; i++)
{
    fftw_complex* in = reinterpret_cast<fftw_complex*>(&x[i]);
    cout << (*in)[0] << " " << (*in)[1] << endl;
}

更新

您还可以像以前一样保持 in 指针定义,并与 for 循环进行交互:

for (int i=0; i<4; i++)
{
    cout << (in[i])[0] << " " << (in[i])[1] << endl;
}
于 2013-09-18T17:00:37.630 回答
-2

首先,永远不要使用 reinterpret_cast,因为这会导致严重的错误。

其次,定义为复数,即具有 2 个双精度数的结构。因此 in[i*2] 将访问由 i*2 索引的 COMPLEX 数,由数组中的双精度数 (i*2)*2 和 (i*2)*2+1 组成。在 i==1 时,您实际上会输出第 4 个复数,而不是第 2 个,并且在 i==2 时,您会超出范围,导致无效的内存访问崩溃或垃圾输出。

于 2013-09-18T16:38:27.133 回答