Skip to content

SYSLIB1054 code fixer should not generate a code that try to access to LibraryImport.ThrowOnUnmappableChar #79159

@Tan90909090

Description

@Tan90909090

Version Used:
Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.4.2

Steps to Reproduce:

  1. Write <TargetFramework>net7.0</TargetFramework> in csproj
  2. Write a following code:
using System;
using System.Runtime.InteropServices;

class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)]
    static extern IntPtr GetProcAddress(
        IntPtr hModule,
        [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

    static void Main() { }
}
  1. Apply a quick-fix Convert to 'LibraryImport' at GetProcAddress

Diagnostic Id:
SYSLIB1054 Mark the method 'GetProcAddress' with 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time

Expected Behavior:
Code fixer generate a code that does not have an error.

Actual Behavior:
Code fixer generate a following code:

using System;
using System.Runtime.InteropServices;

partial class NativeMethods
{
    [LibraryImport("kernel32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Custom, ThrowOnUnmappableChar = true, StringMarshallingCustomType = typeof(System.Runtime.InteropServices.Marshalling.AnsiStringMarshaller))]
    static partial IntPtr GetProcAddress(
        IntPtr hModule,
        [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

    static void Main() { }
}

Because LibraryImportAttribute does not have ThrowOnUnmappableChar member so the above code has an error: CS0246 The type or namespace name 'ThrowOnUnmappableChar' could not be found (are you missing a using directive or an assembly reference?)

Note
I realized that same issue happens to the following code because there is not LibraryImportAttribute.BestFitMapping:

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi, BestFitMapping = true)]
    static extern IntPtr GetProcAddress(
        IntPtr hModule,
        [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions