7

I must pass complex data to a C function from C++. In C++ the data is naturally stored in a std::vector<std::complex> c. The C function expects the data as an array of double, double a[] such that a[0]=Re(c[0]), a[1]=Im(c[0]), a[2]=Re(c[1]), etc.

What is the best safe way to pass such data? Is casting like

(double*) (&c[0])

asking for trouble?

Sorry if this is duplicate, I could only find information on the related problem of passing C++ complex to C99 complex.

TomasG
  • 310
  • 2
  • 9

1 Answers1

19

The C++0x standard went to lengths to guarantee that such conversions will work (§26.4):

Moreover, 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].

and (§23.3.6):

The elements of a vector are stored contiguously, meaning that if v is a vector<T, Allocator> where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

The layout of the complex value is not guaranteed by the prevailing C++03 standard (though the vector layout is), but I would be surprised to find an implementation for which it does not hold.

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
  • Is the C++0x standard already in place? If not, then this guarantee does not necessarily apply to OP (tags are C/C++) – Samaursa Feb 16 '11 at 18:19
  • @Samaursa: I addressed that in the last paragraph of my answer. – Stephen Canon Feb 16 '11 at 18:43
  • Thanks for the answer. I am using GNU C which does not comply wiht C++0x by default (at leas the version I'm running), but I may get the behavior you explain (and which would be very handy for me) explicitly requesting C++0x. – TomasG Feb 16 '11 at 19:43