Search code examples
c#marshallingintptr

How to get IntPtr of the array within List<T>?


I'm using a library which has a function SendBuffer(int size, IntPtr pointer) with IntPtr as a parameter.

 var list = new List<float>{3, 2, 1};
 IntPtr ptr = list.getPointerToInternalArray();
 SendBuffer(ptr, list.Count);

How to get IntPtr from the array stored in List<T> (and/or T[])?


Solution

  • The array is sent every frame and it's big

    In that case it might be warranted to access the internal backing array that List uses. This is a hack and brittle in the face of future .NET versions. That said .NET uses a very high compatibility bar and they probably would not change a field name in such a core type. Also, for performance reasons it is pretty much guaranteed that List will always use a single backing array for its items. So although this is a high risk technique it might be warranted here.

    Or, better yet, write your own List that you control and that you can get the array from. (Since you seem to be concerned with perf I wonder why you are using List<float> anyway because accessing items is slower compared to a normal array.)

    Get the array, then use fixed(float* ptr = array) SendBuffer(ptr, length) to pin it and pass it without copying memory.

    There is not need to use the awkward and slow GCHandle type here. Pinning using fixed uses an IL feature to make this super fast. Should be near zero cost.