Skip to content

LibraryImportGenerator can generate non-compilable code with specific string marshalling (it forgets a global:: on CharSet DllImport properties) #111594

Open
@smourier

Description

@smourier

Description

When using the LibraryImportAttribute attribute on any method, if the project redefines a sub System namespace in the same namespace of generated functions, then the LibraryImportGenerator generates incorrect code.

Reproduction Steps

Here is a .csproj:

<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
		<OutputType>Exe</OutputType>
		<TargetFramework>net9.0</TargetFramework>
		<Nullable>enable</Nullable>
		<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
	</PropertyGroup>

</Project>

And a Program.cs:

using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: DisableRuntimeMarshalling]

namespace ConsoleApp;

internal partial class Program
{
    static void Main()
    {
    }

    [LibraryImport("whatever", StringMarshalling = StringMarshalling.Utf16)]
    public static partial uint Whatever();
}

public class System // this is what causes the generated code to fail to compile
{
}

Expected behavior

The project should compile file.

Actual behavior

Here is the output of CSC:

Rebuild started at 20:06...
1>------ Rebuild All started: Project: ConsoleApp, Configuration: Debug Any CPU ------
Restored E:\smo\work\ConsoleApp\ConsoleApp\ConsoleApp.csproj (in 0,8 ms).
Restored E:\smo\work\ConsoleApp\ConsoleAppFail\ConsoleAppFail.csproj (in 10 ms).
Restored E:\smo\work\ConsoleApp\ClassLibrary1\ClassLibrary1.csproj (in 13 ms).
1>E:\smo\work\ConsoleApp\ConsoleApp\obj\Debug\net9.0\Microsoft.Interop.LibraryImportGenerator\Microsoft.Interop.LibraryImportGenerator\LibraryImports.g.cs(6,144,6,151): error CS0117: 'System' does not contain a definition for 'Runtime'
1>Done building project "ConsoleApp.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
========== Rebuild completed at 20:06 and took 00,409 seconds ==========

As we can see there's CS0117 error: 'System' does not contain a definition for 'Runtime' coming from generated file LibraryImports.g.cs.

Looking at generated source code, it looks something like this:

public static unsafe partial class Functions
{
    [global::System.Runtime.InteropServices.DllImportAttribute("whatever", EntryPoint = "whatever", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
    public static extern partial uint whatever();
}

Where CharSet is missing a global:: prefix.

Regression?

I've not tested under .NET 8 (but I think it's probably there)

Known Workarounds

I don't know any.

Configuration

.NET 9.0.1
Visual Studio 2022 17.12.4
Windows 11 x64

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions