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
2k stars 84 forks source link

Generated extension methods do not correctly handle optional array parameters #1041

Closed BasTossings closed 10 months ago

BasTossings commented 10 months ago

Actual behavior

For example, the generated extension for ID2D1Factory.CreateStrokeStyle is as follows:

internal static unsafe void CreateStrokeStyle(this winmdroot.Graphics.Direct2D.ID2D1Factory @this, in winmdroot.Graphics.Direct2D.D2D1_STROKE_STYLE_PROPERTIES strokeStyleProperties, float[] dashes, out winmdroot.Graphics.Direct2D.ID2D1StrokeStyle strokeStyle)
    {
    fixed (winmdroot.Graphics.Direct2D.D2D1_STROKE_STYLE_PROPERTIES* strokeStylePropertiesLocal = &strokeStyleProperties)
        {
        @this.CreateStrokeStyle(strokeStylePropertiesLocal, dashes, (uint )dashes.Length, out strokeStyle);
        }
    }

The official API documentation states dashes is [in, optional].

when you call CreateStrokeStyle with dashes set to null, you get a NullReferenceException on (uint )dashes.Length.

Expected behavior

The generated extension methods should test for null on optional array parameters.

Repro steps

  1. NativeMethods.txt content:

    ID2D1Factory
  2. NativeMethods.json content (if present):

    {
    "$schema": "https://aka.ms/CsWin32.schema.json",
    "public": false,
    "allowMarshaling": true
    }
  3. Any of your own code that should be shared?

Context

AArnott commented 10 months ago

Thanks for the excellent report.