Last active
February 2, 2023 16:12
-
-
Save asus4/992ae563ca1263b1dd936b970e7fc206 to your computer and use it in GitHub Desktop.
NativeArray -> byte[] , byte[] -> NativeArray
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
using Unity.Collections; | |
using Unity.Collections.LowLevel.Unsafe; | |
namespace ARKitStream.Internal | |
{ | |
public static class NativeArrayExtension | |
{ | |
public static byte[] ToRawBytes<T>(this NativeArray<T> arr) where T : struct | |
{ | |
var slice = new NativeSlice<T>(arr).SliceConvert<byte>(); | |
var bytes = new byte[slice.Length]; | |
slice.CopyTo(bytes); | |
return bytes; | |
} | |
public static void CopyFromRawBytes<T>(this NativeArray<T> arr, byte[] bytes) where T : struct | |
{ | |
var byteArr = new NativeArray<byte>(bytes, Allocator.Temp); | |
var slice = new NativeSlice<byte>(byteArr).SliceConvert<T>(); | |
UnityEngine.Debug.Assert(arr.Length == slice.Length); | |
slice.CopyTo(arr); | |
} | |
public static NativeArray<T> FromRawBytes<T>(byte[] bytes, Allocator allocator) where T : struct | |
{ | |
int structSize = UnsafeUtility.SizeOf<T>(); | |
UnityEngine.Debug.Assert(bytes.Length % structSize == 0); | |
int length = bytes.Length / UnsafeUtility.SizeOf<T>(); | |
var arr = new NativeArray<T>(length, allocator); | |
arr.CopyFromRawBytes(bytes); | |
return arr; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment