Search Unity

Feature Request: Being able to get the pointer to a specific array element

Discussion in 'Entity Component System' started by fholm, Nov 16, 2018.

  1. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    It'd be great if we could get the native pointer to a specific array element from a NativeArray<T>, something like:

    Code (csharp):
    1.  
    2.  public unsafe void* GetReadOnlyElementPointer(int index) {
    3.   CheckElementReadAccess(index);
    4.   return (void*)((byte*)m_Buffer + index * sizeof(T));
    5. }
    6.  
    I can always add it myself of course, but would be cool to have it as a default, maybe this is too low level to add to the public API... could be made into an extension method somewhere?
     
  2. 5argon

    5argon

    Joined:
    Jun 10, 2013
    Posts:
    1,555
    There are some public API to get the first element's pointer. Maybe you could write a wrapper on it to accept index.

    Code (CSharp):
    1. using Unity.Collections.LowLevel.Unsafe;
    Code (CSharp):
    1. NativeArray<int> na = new NativeArray<int>(10, Allocator.Persistent);
    2. void* ptr = NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(na);
    3. void* ptr2 = NativeArrayUnsafeUtility.GetUnsafePtr(na);
     
  3. dartriminis

    dartriminis

    Joined:
    Feb 3, 2017
    Posts:
    157
    What about Read/WriteArrayElement from UnsafeUtility?
    Code (CSharp):
    1.  
    2. var array = new NativeArray<int>(10, Allocator.Temp);
    3. var value = UnsafeUtility.ReadArrayElement<int>(array.GetUnsafePtr(), 5);
    4.