C# WinUSB Can't Call CloseHandle on Interface
CloseHandle() fails when the handle is not a proper kernel32 handle or the handle is already closed. Digging through the github source code, I found out where that problem started:
[DllImport("winusb.dll", SetLastError = true)]
public static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle,
out SafeFileHandle InterfaceHandle);
Edited to fit and make the problem more visible. The type of the 2nd argument is incorrect, the function does not return a kernel32 handle so wrapping it in SafeFileHandle is not correct. This is an opaque handle, a WINUSB_INTERFACE_HANDLE in the native api declaration, typically a pointer under the hood. There is only one correct way to close it, you must call WinUsb_Free(). The code does so, but also calling CloseHandle is not correct and doomed to fail. The CloseHandle() call provided by SafeFileHandle will likewise fail, you probably didn't get that far yet.
Change the argument type to IntPtr
. That requires several other code changes, primarily in the UsbInterface class. Likewise change its Handle property type to IntPtr. Delete the CloseHandle() call in its Dispose() method. Writing your own SafeHandle-derived class to wrap it is another way, you'd then override ReleaseHandle() to call WinUsb_Free().