I must pass complex data to a C function from C++. In C++ the data is naturally stored in a
std::vector. The C function expects the data
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 expressiona[i]is well-defined for an integer expressioni, then:—
reinterpret_cast<cv T*>(a)[2*i]shall designate the real part ofa[i], and—
reinterpret_cast<cv T*>(a)[2*i + 1]shall designate the imaginary part ofa[i].
and (§23.3.6):
The elements of a vector are stored contiguously, meaning that if
vis avector<T, Allocator>whereTis some type other than bool, then it obeys the identity&v[n] == &v[0] + nfor all0 <= 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.