Skip to content

Instantly share code, notes, and snippets.

@redmanmale
Created September 20, 2016 15:04
Show Gist options
  • Save redmanmale/a4840ae3aa906e7325134979f35d5a2d to your computer and use it in GitHub Desktop.
Save redmanmale/a4840ae3aa906e7325134979f35d5a2d to your computer and use it in GitHub Desktop.
Extension method for copy array of structs from pointer (unmanaged memory) to generic collection
internal static class PtrExtensions
{
public static IEnumerable<T> GetArrayOfStruct<T>(this IntPtr ptrToStructArr, int arrSize)
{
var output = new List<T>(arrSize);
var sizeInBytes = Marshal.SizeOf(typeof(T));
for (var i = 0; i < arrSize; i++)
{
#if x64
var ptrToStruct = new IntPtr(ptrToStructArr.ToInt64() + i*sizeInBytes);
#else
var ptrToStruct = new IntPtr(ptrToStructArr.ToInt32() + i*sizeInBytes);
#endif
output.Add(Marshal.PtrToStructure<T>(ptrToStruct));
}
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment