Skip to content

Instantly share code, notes, and snippets.

@asus4
Last active May 10, 2023 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asus4/a19118e04a0682d65cffe5c08911a498 to your computer and use it in GitHub Desktop.
Save asus4/a19118e04a0682d65cffe5c08911a498 to your computer and use it in GitHub Desktop.
Safe Conversion of NativeArray <-> byte[] in Unity
using Unity.Collections;
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment