microsoft / microsoft/CsWin32

Improve friendly overloads when buffers are involved

Open
#1,645 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
C#
Stars
2.5k
Forks
123
Avg merge
1d 3h
Merged PRs (30d)
9

Description

Let's consider current CsWin32 friendly overload of GetUserName function:

BOOL GetUserName([Optional] Span<char> lpBuffer, ref uint pcbBuffer);

This is totally fine from the correctness point of view. But consider the following fact: lpBuffer is an [Optional] pointer to an array, which length is specified in pcbBuffer, which is not optional. In windows APIs such pattern means that user can pass null as a buffer and a pointer to a variable, that will recieve required length. CsWin32 just marks the buffer as [Optional], but for that specific pattern we can do better: generate 2 overloads, in one of which the buffer is not optional, but in the other it is removed and buffer length is turned into out reference:

BOOL GetUserName(Span<char> lpBuffer, ref uint pcbBuffer);
BOOL GetUserName(out uint pcbBuffer);

This very much improves usability of the case when the user wants to get the length upfront since out varible can be declared as it is returned. So the pattern will look like this:

PInvoke.GetUserName(out var requiredLength);
Span<char> data = stackalloc[(int)requiredLength];
uint dataLength = (uint)data.Length;
var err = PInvoke.GetUserName(data, ref dataLength);

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue describes CsWin32's friendly overload generation using GetUserName as the example, but names no files or tests. Start by locating the generator entry point that handles optional buffer parameters and review existing overload-generation tests. Done means generating both the required-buffer overload and the out-length overload while preserving the current behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.