microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Regression with `ReadFile` and `WriteFile` for `SafeHandle`

colejohnson66 opened this issue · comments

Our project recently upgraded from 0.2.188 to 0.3.49. In doing so, ReadFile and WriteFile were changed from taking a SafeHandle to a raw HANDLE.

In 0.2.188, our invocation of ReadFile was:

if (PInvoke.ReadFile(_handle, ptr, (uint)buffer.Length, &bytesRead, overlapped))
    return (int)bytesRead;

In 0.3.49, we are now forced to do the dance that CsWin32 would previously do for us:

bool addedRef = false;
try
{
    // extract a HANDLE from the SafeFileHandle
    _handle.DangerousAddRef(ref addedRef);
    if (PInvoke.ReadFile((HANDLE)_handle.DangerousGetHandle(), ptr, (uint)buffer.Length, &bytesRead, overlapped))
        return (int)bytesRead;
}
finally
{
    _handle.DangerousRelease();
}

Context

  • CsWin32 version: 0.3.49-beta
  • Target Framework: net8.0

I see span overloads were added, so I will assume those are the recommended method of invocation now.