You can use the System.Runtime.InteropServices.GCHandle
struct to pin the managed array in memory and obtain a pointer to it. This allows you to pass the pointer to unmanaged code and treat it as a native array without copying the data.
main.cs405 chars19 lines
The GCHandleType.Pinned
value indicates that the handle is pinned in memory, and the AddrOfPinnedObject()
method returns a pointer to the pinned object. Once you're done with the native array, you need to call handle.Free()
to release the pinned handle.
Note that it's important to keep the managed array pinned for as short a time as possible to minimize the impact on garbage collection.
gistlibby LogSnag