Marshal
您可以通过使用该类的一些手动编组很容易地做到这一点。例如:
[DllImport(@"MyLib.dll")]
private static extern void Foo(IntPtr structPtr);
private static IntPtr StructPtrFromColorTable(int[] colorTable)
{
int size = sizeof(int) + colorTable.Length*sizeof(int);
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.WriteInt32(structPtr, colorTable.Length);
Marshal.Copy(colorTable, 0, structPtr + sizeof(int), colorTable.Length);
return structPtr;
}
private static int[] ColorTableFromStructPtr(IntPtr structPtr)
{
int len = Marshal.ReadInt32(structPtr);
int[] result = new int[len];
Marshal.Copy(structPtr + sizeof(int), result, 0, len);
return result;
}
static void Main(string[] args)
{
int[] colorTable = new int[] { 1, 2, 3 };
IntPtr structPtr = StructPtrFromColorTable(colorTable);
try
{
Foo(structPtr);
colorTable = ColorTableFromStructPtr(structPtr);
}
finally
{
Marshal.FreeHGlobal(structPtr);
}
}