【问题标题】:about memory reference for fftw in c/c++关于 c/c++ 中 fftw 的内存引用
【发布时间】:2013-09-18 16:24:50
【问题描述】:

我正在学习c++中的fftw(替换自定义的fft函数)。在旧代码中,我在 std::vector 样本存储中设计了算法。根据文档,我使用强制转换将 fftw 数据类型与我的数据交互(在 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;
  }
}

但 in 似乎并没有真正指向正确的位置,而是显示随机数。除了上述问题,我的目的是生成一个包含 8 个元素的向量(示例),前 4 个元素指的是 std::vector 但后四个元素被初始化为某个常量。是否有可能让 *in 指向向量中的第一个,然后指向其他地方的 4 个常量值,所以我可以 fftw “in”?谢谢。

【问题讨论】:

  • 我没有理解你的最后一个(第二个)问题。

标签: c++ memory-management fftw


【解决方案1】:

正如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;
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 为什么 reinterpret_cast 会导致严重的错误?他们实际上在 FFTW 网站上推荐它。
    猜你喜欢
    • 2012-06-13
    • 2012-01-24
    • 1970-01-01
    • 2011-03-03
    • 2014-04-11
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多