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

Functions taking HDC do not have friendly overloads taking SafeHandle #1060

Closed jnm2 closed 9 months ago

jnm2 commented 9 months ago

Even though CsWin32 currently doesn't happen to provide DeleteDCSafeHandle or ReleaseDCSafeHandle, I do have such classes that I'd like to pass as SafeHandle without having to do the whole boilerplate dance:

bool thing1NeedsRelease = false;
thing1.DangerousAddRef(ref thing1NeedsRelease);
try
{
    bool thing2NeedsRelease = false;
    thing2.DangerousAddRef(ref thing2NeedsRelease);
    try
    {
        PInvoke.BitBlt((HDC)thing1.DangerousGetHandle(), ..., (HDC)thing2.DangerousGetHandle(), ...);
    }
    finally
    {
        if (thing2NeedsRelease) thing2.DangerousRelease();
    }
}
finally
{
    if (thing1NeedsRelease) thing1.DangerousRelease();
}

This usability issue afflicts BitBlt, CreateDIBSection, DrawIconEx, SelectObject, maybe others. For me, CsWin32 is about not having to intersperse interesting logic with .NET native interop boilerplate. It would be very much in that spirit to always provide SafeHandle overloads any time there is a handle wrapper struct.

Context

AArnott commented 9 months ago

Duplicate of #1049 (but I'll rename it to make this more obvious.)