Skip to content

Instantly share code, notes, and snippets.

@Fireforge
Created July 7, 2016 20:58
Show Gist options
  • Save Fireforge/9e25e883c843dde80b1b568a6b17befa to your computer and use it in GitHub Desktop.
Save Fireforge/9e25e883c843dde80b1b568a6b17befa to your computer and use it in GitHub Desktop.
Useful extensions to the Marshal utilities in C#
public static class MarshalExt
{
// Only needed for .NET 4.5 and earlier
public static T PtrToStructure<T>(IntPtr ptr)
{
return (T)Marshal.PtrToStructure(ptr, typeof(T));
}
public static T[] PtrToStructureArray<T>(IntPtr ptr, int count)
{
var ret = new T[count];
var structSize = Marshal.SizeOf(typeof(T));
for (int i = 0; i < count; i++)
{
ret[i] = PtrToStructure<T>(ptr);
ptr = IntPtr.Add(ptr, structSize);
}
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment