How to get a pointer and a nativeArray using NativeArrayUnsafeUtility

Hi, im trying to figure out how to create a nativeArray from a pointer using NativeArrayUnsafeUtility but all I can get is “Object reference not set to an instance of an object” error!

NativeArray<int> testArray = new(1, Allocator.Temp);
           testArray[0] = 12;

void* pointer = NativeArrayUnsafeUtility.GetUnsafePtr(testArray);

NativeArray<int> recreatedArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(
                                     pointer, testArray.Length, Allocator.Temp);

Debug.Log(testArray[0]); //12
Debug.Log(recreatedArray[0]); //Object reference not set to an instance of an object

You should use Allocator.None to indicate that the array is not the original owner of the data it points to.
Also, make sure the AtomicSafetyHandle is set when the symbol ENABLE_UNITY_COLLECTIONS_CHECKS is defined.

var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(ptr, n, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
#endif
1 Like

Thanks for the quick response.
Adding the safetyHandle fixed the error I was getting.
In my actuall code I want the recreated nativeArray to be the owner of the data so I can dispose it by calling .dispose() on the recreated nativeArray.

So if I understand the documentation correctly I should use Allocator.temp in my case

In that case, yes, that would be appropriate. You would need to use NativeArrayUnsafeUtility.GetAtomicSafetyHandle on the original buffer for correct access safety management.