title: Reading C structures with "union" types from C# with PInvoke
body: <p>I'm trying to bring to managed side (C#) a structure built in C.  </p>
  
  <p>Let's assume this structure (C code):  </p>
  
  <pre><code>typedef struct S{
      int i;
      union{
          TypeA a;
          TypeB b;
          TypeC c;
      }uni;
   } S;  
  </code></pre>
  
  <p>Now, i create the C# wrapper classes:</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  public class S
  {
      [FieldOffset(0)] 
      public int i;
      [FieldOffset(4)] 
      public TypeA a;
      [FieldOffset(4)]
      public TypeB b;
      [FieldOffset(4)]
      public TypeC c;
  }
  </code></pre>
  
  <p>And I have a PInvoke method to get the S object:<br>
  (C's implementation create and return a S structure with a TypeA in union field)</p>
  
  <pre><code>[DllImport("Library.dll", CharSet = CharSet.Auto)]
  [return: MarshalAs(UnmanagedType.S)]
  public static extern S getUnionStruct();
  </code></pre>
  
  <p>Somewhere in main function, I do:</p>
  
  <pre><code>S s = getUnionStruct();
  Console.WriteLine("unions type: {0}",(S.a).GetType());
  </code></pre>
  
  <p>The result is "AssembleName.TypeC" (???)</p>
  
  <p>.net Framework is assuming the TypeC because that was the last declared. I also notice that if the size of TypeC is smaller than TypeA I get unable to read all the TypeA fields..</p>
  
  <p>Is this a bug from .net or I should be doing something different?</p>