A native function for wide or narrow text is declared with the other character set, so its strings are garbled

tx0/csharp:native-charset-mismatchrecommendedwarningreliability/time-and-localedepth fastbug

What it finds

Windows exports most functions that take text twice: CreateFileW takes UTF-16 and CreateFileA takes the ANSI code page. [DllImport] marshals string and StringBuilder as ANSI unless CharSet says otherwise, so a declaration of a ...W function without CharSet = CharSet.Unicode passes one byte per character where the function reads two: names come out garbled or cut short, and buffers overrun. The opposite holds for a ...A function declared with CharSet.Unicode.

Reported are [DllImport] declarations whose entry point, or method name without one, ends in W or A after a lower-case letter, with a string, StringBuilder or char[] parameter without its own [MarshalAs], whose CharSet does not match the suffix. CharSet.Auto is Unicode on every current platform and counts as such.

From the rule's source, native_charset_mismatch.rs.

Example from the rule's tests
using System;using System.Runtime.InteropServices;using System.Text; static class Native{    [DllImport("user32.dll")]    static extern bool SetWindowTextW(IntPtr window, string text);tx0 reports: SetWindowTextW takes UTF-16 text but its strings are marshalled as the default ANSI     [DllImport("kernel32.dll", EntryPoint = "GetModuleFileNameW", CharSet = CharSet.Ansi)]    static extern int ModuleName(IntPtr module, StringBuilder name, int size);tx0 reports: GetModuleFileNameW takes UTF-16 text but its strings are marshalled as ANSI     [DllImport("user32.dll", CharSet = CharSet.Unicode)]    static extern int MessageBoxA(IntPtr owner, string text, string caption, uint type);tx0 reports: MessageBoxA takes ANSI text but its strings are marshalled as Unicode     [DllImport("user32.dll", CharSet = CharSet.Unicode)]    static extern int MessageBoxW(IntPtr owner, string text, string caption, uint type);     [DllImport("user32.dll")]    static extern bool SetWindowTextA(IntPtr window, string text);     [DllImport("kernel32.dll")]    static extern bool DeleteFileW([MarshalAs(UnmanagedType.LPWStr)] string path);     [DllImport("user32.dll")]    static extern IntPtr GetDC(IntPtr window);     [DllImport("gdi32.dll")]    static extern int GetDeviceCapsW(IntPtr dc, int index);}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/csharp:native-charset-mismatch" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/csharp:native-charset-mismatch] reason="..."

tx0 explain tx0/csharp:native-charset-mismatch shows the same in the terminal. Found a false positive? Report it.