开发者

PInvoke returns C type with union

How would I P/Invoke a C function which returns a union'ed struct?开发者_如何学JAVA


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜