问题转换STL复杂< double>到fftw_complex [英] Problem casting STL complex<double> to fftw_complex
问题描述
FFTW手册说,其 fftw_complex
类型与STL中的 std :: complex< double>
类位兼容。但这对我不起作用:
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);
}
这给了我一个错误:
error: invalid cast from type ‘std::complex<double>’ to type ‘double [2]’
我在做什么错了?
推荐答案
重写您的代码如下:
#include <complex>
#include <fftw3.h>
int main()
{
std::complex<double> x(1,0);
fftw_complex fx;
memcpy( &fx, &x, sizeof( fftw_complex ) );
}
我使用的每个编译器都会优化memcpy,因为它正在复制a固定,即在编译时,数据量。
Every compiler I've used will optimise out the memcpy because it is copying a fixed, ie at compile time, amount of data.
这可以避免指针别名问题。
编辑:您还可以避免严格
#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;
}
尽管严格来说,此C99规则(不确定C ++)在阅读时被破坏与定义的工会不同,工会的成员也未定义。尽管它适用于大多数编译器。我个人更喜欢我的原始方法。
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.
这篇关于问题转换STL复杂< double>到fftw_complex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!