Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pin (and get an IntPtr to) a generic T[] array?

Tags:

c#

.net

I want to pin a generically-typed array and get a pointer to its memory:

T[] arr = ...;
fixed (T* ptr = arr)
{
    // Use ptr here.
}

But trying to compile the above code produces this compiler error:

Cannot take the address of, get the size of, or declare a pointer to a managed type

The answers to these questions confirm that there's no way to declare a generic T* pointer. But is there a way to pin a generic T[] array and get an IntPtr to the pinned memory? (Such a pointer still has use because it could be passed to native code or cast to a pointer of known type.)

like image 318
Walt D Avatar asked May 31 '16 20:05

Walt D


1 Answers

Yes, you can use the GCHandle object to pin a generic T[] array and get an IntPtr to its memory while pinned:

T[] arr = ...;
GCHandle handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
// Use the ptr.
handle.Free();

Make sure you remember to call Free(), because otherwise the array will never become unpinned.

like image 145
Walt D Avatar answered Nov 17 '22 01:11

Walt D