When accessing the winapi method CloseHandle() via .net P/Invoke, should the argument be IntPtr or HandleRef, and why?
+1
A:
The HandleRef Structure documentation has a good explanation about its importance. It has to do with the proper functionality of the garbage collector.
Havenard
2009-08-26 06:45:02
+2
A:
It's really your choice, depending on how you obtain the handles. If the handles are originally embedded in some managed object, you should use HandleRef. If you got the handles from other PInvoke functions, and .NET "knows" nothing about them, use IntPtr.
The advantage of HandleRef is that .NET promises to keep the container object alive as long as the HandleRef exists, but then marshals only the handle to the API function. In the specific case of CloseHandle, this doesn't really matter, so IntPtr should be fine.
Martin v. Löwis
2009-08-26 06:47:02