Skip to content

Missing System.Runtime.CompilerServices namespace for Unsafe.Add usage in _e__FixedBuffer int indexer #604

@yaqian256

Description

@yaqian256

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

  1. 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;
  2. Generate C# bindings using ClangSharpPInvokeGenerator

  3. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions