I allocate IntPtr pointing to an array of struct to be used with unmanaged code. I found lot of resources on this subject and here is my final method (seems to work well):
public IntPtr ArrayToPtr<T>(T[] array)
{
int size = array.Length;
int elemSize = Marshal.SizeOf(typeof(T));
IntPtr result = Marshal.AllocHGlobal(elemSize * size);
for (int i = 0; i < size; i++)
{
IntPtr ptr = new IntPtr(result.ToInt64() + elemSize * i);
Marshal.StructureToPtr(array[i], ptr, false);
}
return result;
}
Now my questions:
- How to free properly this resulted IntPtr pointer ? (Is a FreeHGlobal(pointer) is enough ?)
- Is there any precaution to take if I use x86 or x64 system/application platform ?
Same questions for an array of strings (a char** in C):
public IntPtr ArrayOfStringToPtr(string[] array)
{
int size = array.Length;
int elemSize = IntPtr.Size;
IntPtr result = Marshal.AllocHGlobal(elemSize * size);
for (int i = 0; i < size; i++)
{
IntPtr strPtr = Marshal.StringToHGlobalAnsi(array[i]);
Marshal.StructureToPtr(strPtr, new IntPtr(result.ToInt64() + elemSize * i), false);
}
return result;
}