malat
malat

Reputation: 12505

CA2101: Specify marshaling for P-Invoke string arguments

I am trying to expose a C function which takes a UTF-8 string to C# (dotnet 5.0). I am getting a warning which does not make sense to me. Here is a simple way to reproduce it, using fopen(3):

[DllImport("libc.so.6", CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr fopen([MarshalAs(UnmanagedType.LPUTF8Str)] string pathname, string mode);

Visual Studio 2019 is reporting a warning:

enter image description here

From the documentation, it seems I need to set CharSet.Ansi in my case:

and use UnmanagedType.LPUTF8Str:

What did I misunderstood from the documentation ?

Upvotes: 4

Views: 1569

Answers (1)

malat
malat

Reputation: 12505

Technically this is somewhat a duplicate of:

which suggests to add BestFitMapping = false, ThrowOnUnmappableChar = true

In my case the suggested code 'Show potential fixes' ([MarshalAs(UnmanagedType.LPWStr)]) was just bogus (but that is a different issue).

So correct solution is:

[DllImport("libc.so.6", CharSet = CharSet.Ansi, ExactSpelling = true, BestFitMapping = false, ThrowOnUnmappableChar = true, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr fopen([MarshalAs(UnmanagedType.LPUTF8Str)] string pathname, string mode);

Upvotes: 8

Related Questions