Now that C++11 allows you to create unions such as this
union U {
int z;
std::vector<char> data;
};
Is it possible somehow to pass this structure to C library that accepts a regular C union? How?
Now that C++11 allows you to create unions such as this
union U {
int z;
std::vector<char> data;
};
Is it possible somehow to pass this structure to C library that accepts a regular C union? How?
Can you pass that union? No. std::vector
(and all other standard containers except std::array
) will not produce types of a known layout. They may be standard layout types, but no particular layout is presented in the standard. Therefore, you cannot pass it to C.
Note: By "pass it to C," I assume you mean "build an equivalent C structure that has the same memory layout so that C code can touch the data."
But you can pass any union that contains types of a known layout as long as all of the types are standard layout types. They need not be trivial, but they must be standard layout.
Also, if you don't mind being compiler specific, you could look at your particular std::vector
implementation (or use a specific implementation like boost::vector
) and devise an equivalent C structure that stores essentially the same data. Of course, that assumes that the particular implementation is indeed standard layout; the C++ standard doesn't require it to be, and the presence of an allocator might change this.