using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; namespace ARKitStream.Internal { public static class NativeArrayExtension { public static byte[] ToRawBytes(this NativeArray arr) where T : struct { var slice = new NativeSlice(arr).SliceConvert(); var bytes = new byte[slice.Length]; slice.CopyTo(bytes); return bytes; } public static void CopyFromRawBytes(this NativeArray arr, byte[] bytes) where T : struct { var byteArr = new NativeArray(bytes, Allocator.Temp); var slice = new NativeSlice(byteArr).SliceConvert(); UnityEngine.Debug.Assert(arr.Length == slice.Length); slice.CopyTo(arr); } public static void CopyFromRawBytes(byte[] bytes, Allocator allocator, ref NativeArray arr) where T : struct { int length = bytes.Length / UnsafeUtility.SizeOf(); if (!arr.IsCreated || (arr.Length != length)) { if (arr.IsCreated) { arr.Dispose(); } arr = new NativeArray(length, allocator); } arr.CopyFromRawBytes(bytes); } public static NativeArray FromRawBytes(byte[] bytes, Allocator allocator) where T : struct { int structSize = UnsafeUtility.SizeOf(); UnityEngine.Debug.Assert(bytes.Length % structSize == 0); int length = bytes.Length / UnsafeUtility.SizeOf(); var arr = new NativeArray(length, allocator); arr.CopyFromRawBytes(bytes); return arr; } } }