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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With