How can I bind (and get IntPtr) a common array of T []?

I want to bind a typically 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 causes a compiler error:

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

The answers of the questions confirm that there is no way to declare a common T* pointer. But is there a way to bind a shared array of T[] and get IntPtr to pinned memory? (Such a pointer is still used because it can be passed into native code or transferred to a pointer of a known type.)

+6
source share
1 answer

Yes, you can use the GCHandle object to bind a common array T[] and get IntPtr in your memory when pinning:

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

Make sure that you did not call the Free() call, because otherwise the array will never become loose.

+6
source

All Articles