Skip to content

Instantly share code, notes, and snippets.

@asus4
Last active February 2, 2023 16:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save asus4/992ae563ca1263b1dd936b970e7fc206 to your computer and use it in GitHub Desktop.
Save asus4/992ae563ca1263b1dd936b970e7fc206 to your computer and use it in GitHub Desktop.
NativeArray -> byte[] , byte[] -> NativeArray
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