dotnet / roslyn-analyzers

MIT License
1.58k stars 463 forks source link

CA2101 is shown when MarshalAs is not LPStr or LPWStr #5009

Open SupinePandora43 opened 3 years ago

SupinePandora43 commented 3 years ago

Example Input

[DllImport("Ultralight")]
public static extern void ulConfigSetResourcePath(IntPtr config, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ULStringMarshaler))] string resource_path);

Output

image

Steps To Reproduce

  1. define extern method with DllImport Attribute and string argument
  2. specify marshalling using [MarshalAs(UnmanagedType.LPUTF8Str)] or CustomMarshaler
  3. get CA2101
dotnet-issue-labeler[bot] commented 3 years ago

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

Youssef1313 commented 3 years ago

@mavasani Do you have permissions on this repository to move this to dotnet/roslyn-analyzers?

naine commented 3 years ago

I'm finding this is raised even if MarshalAs is LPStr.

[DllImport("mylib", CharSet = CharSet.Ansi, ExactSpelling = true, ThrowOnUnmappableChar = true)]
public static extern void Foo([MarshalAs(UnmanagedType.LPStr)] string s); // CA2102

The only way to satisfy the analyzer seems to be to marshal the string as unicode/utf16, which is not possible if the native API doesn't support that.