Jul 1, 2008

Marshalling Array of Structures

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 [0]);

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++)
   Marshal.StructureToPtr(structArray [index],
         (IntPtr)(addr + structSize * index),false);

The IntPtr type ptr will hold the address of the memory block containing StructType array.


  1. Thank you so much for posting this, I have been having trouble with the exact same problem and couldn't find ANY help online until now. Much appreciated!

  2. Wow thank you so much! i'm finally able to call user32 methods! i was fighting with MarshalAs UnmanagedType.xxArray which doesn't seem work and are also not able to manage dynamic array size..

    lav #1 !!

  3. thanks buddy! it helped .. wish i read u'r blog before trying msdn links :-)