You have to use the StructLayout attribute applied to the class. the StructLayout attribute needs to be passed the parameter LayoutKind.Explicit. This makes it so you can declare the exact offset in the number of Bytes each field will have. Naturally you will need to use another attribute for each of the fields to specify this offset; the name of this attribute is FieldOffset. Both of these Attributes are in the System.Runtime.InteropServices namespace.
Here is an example where 2 32bit integers will share the same memory address as a 64bit integer.
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
public struct PairID
{
public struct PairID
{
[FieldOffset(0)]
public long Id;
[FieldOffset(0)]
public int LowId;
[FieldOffset(sizeof(int))]
public int HighId;
}public long Id;
[FieldOffset(0)]
public int LowId;
[FieldOffset(sizeof(int))]
public int HighId;
No comments:
Post a Comment