views:

80

answers:

2

How would I P/Invoke a C function which returns a union'ed struct?

+4  A: 

You would need to use a StructLayout of explicit and the FieldOffset attribute.

An example of usage:

<StructLayout(LayoutKind.Explicit, Size:=4)> _
   Public Structure DWord
      <FieldOffset(0)> Public Value As Int32
      <FieldOffset(0)> Public High As Int16
      <FieldOffset(2)> Public Low As Int16
   End Structure
DanStory
+2  A: 

To do a simple struct for C, you use [StructLayout(LayoutKind.Sequential)] on a structure. To do a simple union for C, you use [StructLayout(LayoutKind.Explicit)], and give all fields a [FieldOffset(0)]. For more complex structures, nest these two kinds of structures inside each other as appropriate! If this doesn't work correctly you can always analyse the structure generated in C, figure out where all the fields are, and use LayoutKind.Explicit with the correct field offsets for every field.

KernelJ