Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question How to get a pointer and a nativeArray using NativeArrayUnsafeUtility

Discussion in 'Scripting' started by Z0mbie1111, Apr 24, 2024.

  1. Z0mbie1111

    Z0mbie1111

    Joined:
    Sep 13, 2021
    Posts:
    7
    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!

    Code (CSharp):
    1. NativeArray<int> testArray = new(1, Allocator.Temp);
    2.            testArray[0] = 12;
    3.  
    4. void* pointer = NativeArrayUnsafeUtility.GetUnsafePtr(testArray);
    5.  
    6. NativeArray<int> recreatedArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(
    7.                                      pointer, testArray.Length, Allocator.Temp);
    8.  
    9. Debug.Log(testArray[0]); //12
    10. Debug.Log(recreatedArray[0]); //Object reference not set to an instance of an object
     
  2. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    847
    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.
    Code (csharp):
    1. var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(ptr, n, Allocator.None);
    2. #if ENABLE_UNITY_COLLECTIONS_CHECKS
    3. NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.GetTempUnsafePtrSliceHandle());
    4. #endif
     
    Z0mbie1111 likes this.
  3. Z0mbie1111

    Z0mbie1111

    Joined:
    Sep 13, 2021
    Posts:
    7
    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
     
  4. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    847
    In that case, yes, that would be appropriate. You would need to use NativeArrayUnsafeUtility.GetAtomicSafetyHandle on the original buffer for correct access safety management.
     
    Last edited: Apr 24, 2024