dotnet / pinvoke

A library containing all P/Invoke code so you don't have to import it every time. Maintained and updated to support the latest Windows OS.
MIT License
2.12k stars 222 forks source link

Kernel32.GetModuleHandle should return IntPtr instead of SafeHandle #563

Closed HavenDV closed 3 years ago

HavenDV commented 3 years 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.

zgabi commented 3 years ago

Maybe it should retun a SafeHandle with ownsHandle=false.

AArnott commented 3 years ago

@zgabi That would be great if .NET offered a way to do that. AFAIK it does not.

zgabi commented 3 years ago

@AArnott : you mean that the .net marshalling can't reate SafeHandle with ownsHandle=false?

in this case a private method shoudl created (with a differnt name or in an internal class): private static extern IntPtr GetModuleHandle(string lpModuleName); And create a wrapper:

        public static SafeLibraryHandle GetModuleHandle(string lpModuleName)
        {
            return new SafeLibraryHandle(GetModuleHandleInt(lpModuleName), false);
        }

Or create a request to MS to allow to return a SafeHandle with ownsHandle=false with an attribute :)

AArnott commented 3 years ago

you mean that the .net marshalling can't reate SafeHandle with ownsHandle=false

Yes, that's my meaning.

Yes, a wrapper method can help resolve this problem. You could do this in your own code as well.

8 commented 3 years ago

Hi,

I just stumbled over the same bug and found this issue and that it is already fixed via IntPtr return.

Is there some release available with this fix included that I could use? I am using:

<PackageReference Include="PInvoke.User32" Version="0.7.78" />

and this still returns the safe handle and I've looked for a prerelease version, but didn't find any.

Is there something more that needs to be done, before it can be released that I am missing?

Thanks for the great project!

Take care, Martin

AArnott commented 3 years ago

Sure. Watch for 0.7.104 to release to nuget shortly.

8 commented 3 years ago

Thank you! Thanks a lot for your work - the library is great productivity booster!