mal*_*lat 4 c# pinvoke character-encoding
我正在尝试公开一个 C 函数,该函数将 UTF-8 字符串传递给 C# (dotnet 5.0)。我收到一条对我来说没有意义的警告。这是使用 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);
Run Code Online (Sandbox Code Playgroud)
Visual Studio 2019 报告警告:
从文档来看,我似乎需要CharSet.Ansi在我的情况下进行设置:
并使用UnmanagedType.LPUTF8Str:
我从文档中误解了什么?
从技术上讲,这有点重复:
这建议添加BestFitMapping = false, ThrowOnUnmappableChar = true
就我而言,建议的代码“显示潜在的修复”([MarshalAs(UnmanagedType.LPWStr)])只是伪造的(但这是一个不同的问题)。
所以正确的解决方案是:
[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);
Run Code Online (Sandbox Code Playgroud)