Created
July 7, 2016 20:58
-
-
Save Fireforge/9e25e883c843dde80b1b568a6b17befa to your computer and use it in GitHub Desktop.
Useful extensions to the Marshal utilities in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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