Missing System.Runtime.CompilerServices namespace for Unsafe.Add usage in _e__FixedBuffer int indexer
Description
The ClangSharpPInvokeGenerator (version 20.1.2.1) fails to generate a necessary using System.Runtime.CompilerServices; statement when generating code that uses the Unsafe class within the int indexer of _e__FixedBuffer type implementations.
Steps to Reproduce
-
Create a C header file with a struct containing a flexible array member:
typedef struct _Frame_t { unsigned int Length; unsigned char Data[1]; } Frame_t; -
Generate C# bindings using
ClangSharpPInvokeGenerator -
Examine the generated code, which contains a reference to
Unsafe.Add(...)but lacks the required namespace import. This results in compilation error CS0103: The name 'Unsafe' does not exist in the current context.
Reproduction Repository
A minimal reproduction project is available at: https://github.com/yaqian256/Samples/tree/main/ClangSharpBug Build the project in Visual Studio or using the dotnet CLI will reproduce the error.
Actual Results
The generated code includes references to the Unsafe class without importing the necessary namespace:
public partial struct _Data_e__FixedBuffer
{
public byte e0;
[UnscopedRef]
public ref byte this[int index]
{
get
{
return ref Unsafe.Add(ref e0, index); // Compilation error: CS0103: The name 'Unsafe' does not exist in the current context.
}
}
[UnscopedRef]
public Span<byte> AsSpan(int length) => MemoryMarshal.CreateSpan(ref e0, length);
}
This results in compilation error CS0103: The name 'Unsafe' does not exist in the current context.
Expected Results
The generator should include the required namespace import:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices; // Missing namespace
using System.Runtime.InteropServices;
Environment Information
- ClangSharpPInvokeGenerator version: 20.1.2.1
- OS: Windows
- .NET version: net9.0