'In Unity, how do you create a collection of pointers?

Is it possible to create a list or array of pointers in C#?

I want to have a list of T* rather than use IntPtr because i am forever having to type Marshal Ptr To Structure methods all over the place rather than directly access methods via -> command.

I tried making a list with T* but it says it cannot use it as a type. So is my only option to just constantly convert when needed from the IntPtr ?



Solution 1:[1]

  1. You can declare an array of pointer.

    unsafe Vector3*[] vectorPointerArray;
    
  2. You cannot use pointer as a generic type parameter like List<Vector3*>, this is still under consideration.

  3. Because of the feasibility 1, you can create a collection to hold pointers, though it cannot implement generic interfaces like IList<T>.

    unsafe class UnsafePointerList<T> where T : unmanaged
    {
        private T*[] _items;
        public T* this[int index] => _items[index];
    }
    
    UnsafePointerList<Vector3> vectorPointerList;
    var x = vectorPointerList[0]->x;
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1