DllImportAttribute.CharSet 字段


指示如何向方法封送字符串参数,并控制名称重整。Indicates how to marshal string parameters to the method and controls name mangling.

public: System::Runtime::InteropServices::CharSet CharSet;
public System.Runtime.InteropServices.CharSet CharSet;
val mutable CharSet : System.Runtime.InteropServices.CharSet
Public CharSet As CharSet 




下面的代码示例演示如何使用 DllImportAttribute 特性导入 Win32 MessageBox 函数。The following code example shows how to use the DllImportAttribute attribute to import the Win32 MessageBox function. 然后,该代码示例调用导入的方法。The code example then calls the imported method.

using System;
using System.Runtime.InteropServices;

class Example
    // Use DllImport to import the Win32 MessageBox function.
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
    static void Main()
        // Call the MessageBox function using platform invoke.
        MessageBox(new IntPtr(0), "Hello World!", "Hello Dialog", 0);
Imports System.Runtime.InteropServices

Module Example

    ' Use DllImport to import the Win32 MessageBox function.
    <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _
    Function MessageBox(ByVal hwnd As IntPtr, ByVal t As String, ByVal caption As String, ByVal t2 As UInt32) As Integer
    End Function

    Sub Main()
        ' Call the MessageBox function using platform invoke.
        MessageBox(New IntPtr(0), "Hello World!", "Hello Dialog", 0)
    End Sub

End Module


将此字段与 CharSet 枚举的成员一起使用,以指定字符串参数的封送处理行为,并指定要调用的入口点名称(给定的准确名称或以 "A" 或 "W" 结尾的名称)。Use this field with a member of the CharSet enumeration to specify the marshaling behavior of string parameters and to specify which entry-point name to invoke (the exact name given or a name ending with "A" or "W"). C#和 Visual Basic 的默认枚举成员是 CharSet.Ansi,的C++默认枚举成员是 CharSet.None,它等效于 CharSet.AnsiThe default enumeration member for C# and Visual Basic is CharSet.Ansi and the default enumeration member for C++ is CharSet.None, which is equivalent to CharSet.Ansi. 在 Visual Basic 中,使用 Declare 语句指定 CharSet 字段。In Visual Basic, you use the Declare statement to specify the CharSet field.

ExactSpelling 字段会影响 CharSet 字段的行为,以确定要调用的入口点名称。The ExactSpelling field influences the behavior of the CharSet field in determining which entry-point name to invoke. 有关与 CharSet 字段相关联的字符串封送处理和名称匹配行为的详细说明和示例,请参阅指定字符集For a detailed description and examples of the string marshaling and name matching behavior associated with the CharSet field, see Specifying a Character Set.