问题
Possible Duplicate:
Passing a C++ complex array to C
If a third party C library expects an array of C99 complex numbers as an argument, what is the easiest way to call it from C++, where my complex numbers use the STL complex type? I could just wrap it in a new c function that accepts floats and converts them to complex, but is there a more direct way to do it?
回答1:
According to C99:
6.2.5/13 Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.
and according to C++11:
26.4 if
a
is an expression of typecv* std::complex<T>*
and the expressiona[i]
is well-defined for an integer expressioni
, then:
reinterpret_cast<cv T*>(a)[2*i]
shall designate the real part ofa[i]
, andreinterpret_cast<cv T*>(a)[2*i + 1]
shall designate the imaginary part ofa[i]
Together, these mean that the two types have the same layout, so you can simply pass the C function a pointer to the array of std::complex
.
Note that older versions of C++ did not guarantee this layout.
来源:https://stackoverflow.com/questions/14569690/supply-c99-complex-arguments-from-c