Created
September 20, 2016 15:04
-
-
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
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
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