microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
1.99k stars 84 forks source link

GetModuleHandle incorrectly returns a FreeLibrarySafeHandle #1068

Closed riverar closed 8 months ago

riverar commented 8 months ago

The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. However, if this handle is passed to the FreeLibrary function, the reference count of the mapped module will be decremented. Therefore, do not pass a handle returned by GetModuleHandle to the FreeLibrary function. Doing so can cause a DLL module to be unmapped prematurely.

https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea

AArnott commented 8 months ago

Duplicate of #644, which by the way was resolved by honoring DoNotRelease attributes in the metadata. While CsWin32's friendly overload does return a safe handle, it's an object that will not release the handle (it's created with ownsHandle: false).

The SafeHandle return type is believed to be useful for other reasons (e.g. for passing to another API that requires a SafeHandle parameter type), even if it never releases the native handle.