【问题标题】:CA2101: Specify marshaling for P-Invoke string argumentsCA2101:为 P-Invoke 字符串参数指定封送处理
【发布时间】:2021-04-16 13:50:46
【问题描述】:

我正在尝试公开一个将 UTF-8 字符串传递给 C# (dotnet 5.0) 的 C 函数。我收到了warning,这对我来说没有意义。这是一个使用 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 报告警告:

从文档看来,我需要设置CharSet.Ansi

并使用UnmanagedType.LPUTF8Str:

我从文档中误解了什么?

【问题讨论】:

    标签: c# character-encoding pinvoke


    【解决方案1】:

    从技术上讲,这有点重复:

    建议添加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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      相关资源
      最近更新 更多