日期:2014-05-18  浏览次数:20835 次

求C#内存对齐示例代码
最好是结构体的示例代码,不用太复杂。。。谢谢了

------解决方案--------------------
Explicit Layout Example 
This example below shows the use of explicit layout so that fields are not laid out sequentially, and it also intentionally overlaps some data to create a C-style discriminated union: 

using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct MyUnion
{
[FieldOffset(0)] string someText;
[FieldOffset(7)] byte additionalData;
[FieldOffset(6)] byte unionTag; // 0 = ‘a’, 1 = ‘b’
[FieldOffset(4)] short unionA;
[FieldOffset(4)] byte unionB1;
[FieldOffset(5)] byte unionB2;
}The first 4 bytes are taken up by the someText managed reference. Then we intentionally start the unionA and unionB1 fields after the 4th byte. unionA is a short and thus takes up 2 bytes, whereas unionB1 is only a single byte. We then pack another byte after unionB2, which overlaps with the second byte of unionA. After this, we have a single byte to indicate which type the union is. The intention is that if unionTag is 0, unionA contains valid data; otherwise, both unionB1 and unionB2 contain valid data. We then store some additionalData (a single byte) in the last byte.