Created
November 30, 2018 07:18
-
-
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
This file contains 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 Kern32 { | |
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] | |
public static extern void CopyMemory(System.IntPtr dest, System.IntPtr src, uint count); | |
} |
This file contains 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 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