When you are passing an unmanaged handle (stored in either IntPtr or SafeHandle at the managed side) from managed to unmanaged code to do overlapped I/O, what is the correct approach?
- use a SafeHandle to wrap the (IntPtr) OS handle in,
- or use GCHandle.Alloc(IntPtrHandle, GCHandleType.Pinned) to pin it?
I am currently using a SafeHandle in combination with a NativeOverlapped structure, but I'm beginning to suspect more and more that GC is moving either or both around in memory while unmanaged overlapped IO is in progress.
Would I better go back to using an IntPtr instead of a SafeHandle, and use a GCHandle structure to pin it?
Or is the right way a combination of all, i.e. in your NativeOverlapped, use a pinned version of the IntPtr which is in its turn coming from the SafeHandle?
-- EDIT
Reflecting about this during lunch, I got the idea that I'm being stupid. It must be the overlapped structure that needs to be pinned, not the handle in it. Is that the right (best) answer?