字符集和封送Charsets and marshaling

char 值、string 对象和 System.Text.StringBuilder 对象的封送方式取决于 P/Invoke 或结构上的 CharSet 字段的值。The way char values, string objects, and System.Text.StringBuilder objects are marshaled depends on the value of the CharSet field on either the P/Invoke or structure. 可以通过在声明 P/Invoke 时设置 DllImportAttribute.CharSet 字段来设置 P/Invoke 的 CharSetYou can set the CharSet of a P/Invoke by setting the DllImportAttribute.CharSet field when declaring your P/Invoke. 若要为类型设置 CharSet,请在类或结构声明中设置 @no__t 字段。To set the CharSet for a type, set the StructLayoutAttribute.CharSet field on your class or struct declaration. 未设置这些属性字段时,将由语言编译器确定使用哪些 CharSetWhen these attribute fields are not set, it is up to the language compiler to determine which CharSet to use. C# 和 VB 默认使用 Ansi 字符集。C# and VB use the Ansi charset by default.

下表显示了每个字符集之间的映射以及字符或字符串在使用该字符集封送时的表示形式:The following table shows a mapping between each charset and how a character or string is represented when marshaled with that charset:

CharSetCharSet value WindowsWindows Unix 上的 .NET Core 2.2 及更低版本.NET Core 2.2 and earlier on Unix Unix 上的 .NET Core 3.0 及更高版本和 Mono.NET Core 3.0 and later and Mono on Unix
AnsiAnsi char(系统默认的 Windows (ANSI) 代码页char (the system default Windows (ANSI) code page) char (UTF-8)char (UTF-8) char (UTF-8)char (UTF-8)
UnicodeUnicode wchar_t (UTF-16)wchar_t (UTF-16) char16_t (UTF-16)char16_t (UTF-16) char16_t (UTF-16)char16_t (UTF-16)
自动Auto wchar_t (UTF-16)wchar_t (UTF-16) char16_t (UTF-16)char16_t (UTF-16) char (UTF-8)char (UTF-8)

确保了解选择字符集时所需的本机表示形式。Make sure you know what representation your native representation expects when picking your charset.