There are three ways to define a .NET structure:
With LayoutKind.Auto, the CLR chooses how to arrange the fields in the structure based on its own optimizations. You should not use this on any structure that will be used with unmanaged code.
With LayoutKind.Explicit, the fields of the structure are arranged by using byte offsets.
With LayoutKind.Sequential, the fields are arranged in the order they appear in the structure definition. Here is an example:
[StructLayout(LayoutKind.Sequential]
public struct MyUnion
{
public long MyLong;
public char MyChar;
public string MyString;
}
Since .NET does not contain unions as a built-in feature, you are forced to use struct and modify it. A big limitation of this is that you cannot use reference types in the union. Here is an example:
[StructLayout(LayoutKind.Explicit]
public struct MyUnion
{
public long MyLong;
[FieldOffset(0)] public int MyInt;
[FieldOffset(0)] public long MyLong;
[FieldOffset(0)] public short MyShort;
}
The IntPtr class allows you to store pointers in managed code. It is commonly used in scenarios where you are dealing with struct**, C-style arrays, by-reference value types that could be null, VARIANT s containing structures, and SAFEARRAY s containing VARIANT s containing structures. (The next section presents an example of passing an array of interface pointers.) The following example demonstrates using the IntPtr class.
using System;
using System.Runtime.InteropServices;
namespace Client.Chapter_10___ COM and .NET Interoperability
{
public class TestClass
{
[STAThread]
static void Main(string[] args)
{
IntPtr ptr = IntPtr.Zero;
ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(int)));
Marshal.FreeHGlobal(ptr);
}
}
}