2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity - "NativeArray<T> where T:struct" の要素を "T[] where T:struct" へ高速にコピーする

Posted at

Marsha.CopyTo() には IntPtr -> IntPtr のコピーメソッドがないので、kernel32.dll にある CopyMemory() を使う。

public static class Kern32 {
	[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
	public static extern void CopyMemory(System.IntPtr dest, System.IntPtr src, uint count);
}

"T[] where T:struct" は Generic なので fixed ブロックでポインタに変換できない。Marsha.UnsafeAddrOfPinnedArrayElement() で配列の最初のポインタが取れるのでそれを利用する。その前に、GC されないように Pinned データに指定しておく。

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();
			}
		}
	}
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?