1

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?

user841550
  • 1,067
  • 3
  • 16
  • 25
  • 7
    Won't the `std::vector` be a bigger problem? – Ry- Apr 10 '12 at 00:04
  • @minitech I was thinking may be you could pass the pointer like so &data[0] – user841550 Apr 10 '12 at 00:12
  • 1
    @user841550 : Right, but then you're not passing an instance of the union, which begs the question... – ildjarn Apr 10 '12 at 00:21
  • @ildjarn You are right. I don't know the real answer, that's why I am asking. I thought the designers may have thought about some compiler magic that would allow us to pass such a union to C functions – user841550 Apr 10 '12 at 00:38
  • +1 for question. Obviously C can't do anything with an instance of `U` which contains a `vector`, but it's reasonable to wonder if you can pass an instance of `U` when it contains just an `int`. Remember, C has strict layout-compatibility rules. – MSalters Apr 10 '12 at 07:45

1 Answers1

2

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.

Community
  • 1
  • 1
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982