Skip to content

Instantly share code, notes, and snippets.

@GTANAdam
Last active April 5, 2021 12:00
Show Gist options
  • Select an option

  • Save GTANAdam/77604a4924d48a9acd3eaa0b8c9e0819 to your computer and use it in GitHub Desktop.

Select an option

Save GTANAdam/77604a4924d48a9acd3eaa0b8c9e0819 to your computer and use it in GitHub Desktop.
Marshalling a pointer to an array of structures (C/C++/C# Interop)
public unsafe static void MarshalPtrToStructureArray<T>(IntPtr sPtr, ulong arrSize, ref T[] output) where T : unmanaged
{
fixed (T* dPtr = output)
{
ulong dataSize = arrSize * (uint)Marshal.SizeOf(typeof(T));
Unsafe.CopyBlock(dPtr, (void*)sPtr, (uint)dataSize);
// Alternatively, .NET Framework >= 4.6
// ulong dataSize = arrSize * (uint)Marshal.SizeOf<T>();
// Buffer.MemoryCopy((void*)sPtr, dPtr, dataSize, dataSize);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment