Eugen1344
Eugen1344

Reputation: 175

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

Upvotes: 3

Views: 8131

Answers (3)

Kalvin Couto
Kalvin Couto

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

zwcloud
zwcloud

Reputation: 4889

It IS possible.

  1. You can access the private array filed List<T>._items by reflection.

  2. 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

xxbbcc
xxbbcc

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

Related Questions