当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: