Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray, am I doing it right?

Discussion in 'Entity Component System' started by ahmidou, Jan 18, 2019.

  1. ahmidou

    ahmidou

    Joined:
    Sep 17, 2012
    Posts:
    87
    Hi,
    I was wondering if this was safe and wouldn't result in a memory leak

    Code (CSharp):
    1. public static unsafe void CastToNativeArray(NativeArray<Vector3> array, ref NativeArray<float> nArray, int length)
    2. {
    3.     void* ptr = array.GetUnsafePtr<Vector3>();
    4.     nArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float>(ptr, length * 3, Allocator.None);
    5.     NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nArray, AtomicSafetyHandle.Create());
    6. }
    7.  
    8.  
    9. // Let suppose this NativeArray is a memeber of a Monobehavior
    10. private NativeArray<float> nVertices
    11.  
    12. // then in Start()
    13. var vertices = mesh.vertices;
    14. CastToNativeArray(vertices, ref nVertices);
    15.  
    16. // I fist  thought I'd need to do that at the end, but it seems not
    17. AtomicSafetyHandle handle = NativeArrayUnsafeUtility.GetAtomicSafetyHandle(nVertices);
    18. AtomicSafetyHandle.CheckDeallocateAndThrow(handle);
    19. AtomicSafetyHandle.Release(handle);
    20.  
    21.  
    Thanks
     
    deus0 likes this.
  2. ahmidou

    ahmidou

    Joined:
    Sep 17, 2012
    Posts:
    87
    Basically, trying to release it returns an error, @Joachim_Ante maybe ?