Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SafeFileHandle in DLL import

Tags:

c#

pinvoke

It's the first time I need to use P/Invoke to interact with device driver. In DeviceIoControl function I use SafeFileHandle for handle to the device and pinvoke.net says:

If you use a SafeFileHandle, do not call CloseHandle as the CLR will close it for you.

But in C# Cookbook I found this kind signature of CloseHandle:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(SafeFileHandle hObject);

What's the truth?

like image 755
Oksana Avatar asked Mar 01 '13 09:03

Oksana


2 Answers

SafeFileHandle internally calls CloseHandle in its ReleaseHandle method, and is designed to be used in with a Disposable pattern, so you don't want to manually close the handle with CloseHandle(SafeFileHandle) (just call the Close method, or Dispose, instead).

And as SafeFileHandle is sealed, I really don't see any point in the "public static extern bool CloseHandle(SafeFileHandle hObject);" signature.


EDIT

I just googled your book and found one CloseHandle(SafeFileHandle) reference. As expected, it is not used, and the SafeFileHandle is properly closed using:

private void ClosePipe() 
{ 
    if (!_handle.IsInvalid) 
    { 
        _handle.Close(); 
    } 
}
like image 153
ken2k Avatar answered Nov 18 '22 21:11

ken2k


What you see there is the Win32-API function to close an open handle. This function is to be used when you are using Win32-C/C++ and work with system-handles. I cannot validate the above statement a 100% about the CLR, but I guess you will be fine, not to use it.

See the MSDN-article on CloseHandle-function for Win32.

Also there is this article here, which talks about the GC of the CLR.

like image 32
bash.d Avatar answered Nov 18 '22 23:11

bash.d