Search code examples
c#unmanaged

How to get a pointer of list?


So i know that list holds array inside it, so i need to get a pointer of unknown type of it (void*). It is pretty easy to do with arrays:

int[] items;
fixed (void* pointer = items)
{

}

So i need to do same thing for List

List<int> items;
fixed (void* pointer = items)
{

}

This code doesn't seems to work. I don't want to copy a list to a new array, i want to access a pointer to it's internal array


Solution

  • I use this, Just use it carefully and you won't have any problems.

    public static Span<T> AsSpan<T>(this List<T> list) where T : unmanaged
    {
        return CollectionsMarshal.AsSpan(list);
    }
    
    public static ref T AsRef<T>(this List<T> list, int index) where T : unmanaged
    {
        return ref CollectionsMarshal.AsSpan(list)[index];
    }