Reputation: 175
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
Upvotes: 3
Views: 8131
Reputation: 66
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];
}
Upvotes: 4
Reputation: 4889
It IS possible.
You can access the private array filed List<T>._items
by reflection.
Implement one yourself!
Take advantage of the open-sourced .NET Core project, it's free: source code of List<T>
. Then adding methods or something to get a unsafe pointer of List<T>._items
is very easy.
Upvotes: 5
Reputation: 17327
It's not possible to get a pointer to a List<T>
- you can only get pointers to arrays of primitive types. (In that case, you get a pointer to the first element by getting its address.)
Depending on how big your list is, you can call ToArray()
on the list and then get a pointer to the first element but this could be fairly expensive for large arrays.
Upvotes: 1