找回密码
 立即注册

QQ登录

只需一步,快速开始

graper

高级会员

45

主题

63

帖子

1348

积分

高级会员

积分
1348

活字格认证

[迁移] Unions in C#

graper
高级会员   /  发表于:2009-12-15 11:41  /   查看:6863  /  回复:0
Post by "Shrek",  09-26-2007, 11:56
-----------------------------------------------------


Usage of unions in the native world is pretty common. However, the same is not true for the .NET world. However, while using interop sometimes you need to fiddle around this these.

In C# you go about defining unions using the Explicit layout supported by struct as follows.

[StructLayout(LayoutKind.Explicit)]public struct MyUnion{    [FieldOffset(0)]    public UInt16 myInt;    [FieldOffset(0)]    public Byte byte1;    [FieldOffset(1)]    public Byte byte2;}Here the StructLayout(LayoutKind.Explicit) is used to indicate that the stuct definition contains the layout explicitely. FieldOffset(offset) is used to specify the offset of the struct field from the start of the struct.

In the example above the layout of the struct is somewhat as follows

<<===== MyUnion (16 bits)====>>
+--------------------------------------+
|                    myInt (16-bit)                 |
+------------------+-------------------+
|    byte1 (8 bit)      |     byte2 (8 bit)     |
+------------------+-------------------+

byte1 and byte2 share storage with myInt. The following code prints them out and highlight the fact that the system I used (Intel processor based) is little-endian.
  1. MyUnion union;union.byte1 = 0; // needed to make the compiler happy
  2. union.byte2 = 0;
  3. union.myInt = 0xAABB;
  4. Console.WriteLine("{0:X}", union.byte1);
  5. Console.WriteLine("{0:X}", union.byte2);
复制代码
// output is
BB
AA
Since the system is little-endian the LSB (0xBB) goes to the first byte and the MSB (0xAA)goes to the second.

<rant>

All this is very cool. The only thing that made me a bit unhappy is that the definite assignment verifier couldn't figure out that I needn't do the byte1, byte2 assignment to access them.

</rant>

0 个回复

您需要登录后才可以回帖 登录 | 立即注册
返回顶部