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?

Community
  • 1
  • 1
Fadecomic
  • 1,220
  • 1
  • 10
  • 23

1 Answers1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • In C++11 the layout *is* defined to be the same as in C99. See section 26.4. – Bo Persson Jan 28 '13 at 20:42
  • I like this answer, though I wish there was a way to do it without copying the data. The array in the code of interest can easily be millions of double precision complex numbers in size. But if the `std::complex` type is not of the same layout, I'll either have to redesign or copy. – Fadecomic Jan 28 '13 at 21:46
  • @BoPersson: So it is. I only looked at the class definition, and didn't notice that part of the preamble. – Mike Seymour Jan 29 '13 at 01:22
  • 1
    @Fadecomic: Actually you're in luck: I missed the clause of the C++ standard that specified the layout to be the same as the C types. See the updated answer. – Mike Seymour Jan 29 '13 at 01:29