3

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?

4

1 回答 1

4

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 type cv* std::complex<T>* and the expression a[i] is well-defined for an integer expression i, then:

  • reinterpret_cast<cv T*>(a)[2*i] shall designate the real part of a[i], and
  • reinterpret_cast<cv T*>(a)[2*i + 1] shall designate the imaginary part of a[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.

于 2013-01-28T19:48:21.967 回答