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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Can you pass that union? No.
std::vector(and all other standard containers exceptstd::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::vectorimplementation (or use a specific implementation likeboost::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.