Skip to content

Instantly share code, notes, and snippets.

@nobnak
Created November 30, 2018 07:18
Show Gist options
  • Save nobnak/e54310995542f7d8f85078c6c61fdb3f to your computer and use it in GitHub Desktop.
Save nobnak/e54310995542f7d8f85078c6c61fdb3f to your computer and use it in GitHub Desktop.
Unity - "NativeArray<T> where T:struct" の要素を "T[] where T:struct" へ高速にコピーする ref: https://qiita.com/nobnak/items/a55385e22758731f4532
public static class Kern32 {
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
public static extern void CopyMemory(System.IntPtr dest, System.IntPtr src, uint count);
}
public static class NativeArrayExtension {
public static void UnsafeCopyTo<T>(this NativeArray<T> src, T[] dst) where T:struct {
unsafe {
var pSrc = (System.IntPtr)src.GetUnsafePtr();
var hDst = GCHandle.Alloc(dst, GCHandleType.Pinned);
try {
var pDst = Marshal.UnsafeAddrOfPinnedArrayElement(dst, 0);
Kern32.CopyMemory(pDst, pSrc, (uint)(dst.Length * Marshal.SizeOf<T>()));
} finally {
hDst.Free();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment