Last active
May 10, 2023 12:12
-
-
Save asus4/a19118e04a0682d65cffe5c08911a498 to your computer and use it in GitHub Desktop.
Safe Conversion of NativeArray <-> byte[] in Unity
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; | |
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