It is fairly easy to Marshal simple structures in .NET but when it comes to sending a whole bunch of structures as parameter it’s little head scratching task if you have not done it already. The worst part is you won’t find any articles on how one should go about it. When I had to marshal an array of structures, every time I ran into same state of confusion. I decided to blog it this time (for future reference of course :) )
So let’s assume there is a structure called StructType and structArray be an array of StructType.
//Lets not bother about how the array was populated
StructType structArray = new GetStructArray();
// Get the size of each element
int structSize = Marshal.SizeOf(structArray );
Here int can be replaced with long (depends on 32 bit or 64 bit addressing)
// Total size of the memory block
IntPtr ptr = Marshal.AllocHGlobal(structSize * structArray.Length);
int addr = (int)ptr;
for (int index = 0; index < structArray.Length; index++)
(IntPtr)(addr + structSize * index),false);
The IntPtr type ptr will hold the address of the memory block containing StructType array.