-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
Version Used:
Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.4.2
Steps to Reproduce:
- Write
<TargetFramework>net7.0</TargetFramework>in csproj - 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() { }
}- Apply a quick-fix
Convert to 'LibraryImport'atGetProcAddress
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);