指定入口点

入口点标识 DLL 中函数的位置。 在托管项目中,目标函数的原始名称或序号入口点跨越互操作边界标识该函数。 此外,可以将入口点映射到其他名称,从而有效地重命名函数。

下面是重命名 DLL 函数的可能原因列表:

  • 避免使用区分大小写的 API 函数名称

  • 符合现有的命名标准

  • 以适应采用不同数据类型的函数(通过声明同一 DLL 函数的多个版本)

  • 简化使用包含 ANSI 和 Unicode 版本的 API

本主题演示如何在托管代码中重命名 DLL 函数。

在 Visual Basic 中重命名函数

Visual Basic 使用 Function 语句中的 Declare 关键字来设置 DllImportAttribute.EntryPoint 字段。 下面的示例演示了一个基本声明。

Friend Class NativeMethods
    Friend Declare Auto Function MessageBox Lib "user32.dll" (
        ByVal hWnd As IntPtr,
        ByVal lpText As String,
        ByVal lpCaption As String,
        ByVal uType As UInteger) As Integer
End Class

可以通过在定义中包含Alias关键字来将MessageBox入口点替换为MsgBox,如以下示例所示。 在这两个示例中, Auto 关键字都无需指定入口点的字符集版本。 有关选择字符集的详细信息,请参阅 指定字符集

Friend Class NativeMethods
    Friend Declare Auto Function MsgBox _
        Lib "user32.dll" Alias "MessageBox" (
        ByVal hWnd As IntPtr,
        ByVal lpText As String,
        ByVal lpCaption As String,
        ByVal uType As UInteger) As Integer
End Class

在 C# 和 C++ 中重命名函数

可以使用 DllImportAttribute.EntryPoint 字段按名称或序号指定 DLL 函数。 如果方法定义中的函数名称与 DLL 中的入口点相同,则无需使用字段显式标识函数 EntryPoint 。 否则,请使用以下属性形式之一来指示名称或序号:

[DllImport("DllName", EntryPoint = "Functionname")]
[DllImport("DllName", EntryPoint = "#123")]

请注意,序号前必须带有井号 (#)。

以下示例演示如何使用EntryPoint字段在代码中将MessageBoxA替换为MsgBox

using System;
using System.Runtime.InteropServices;

internal static class NativeMethods
{
    [DllImport("user32.dll", EntryPoint = "MessageBoxA")]
    internal static extern int MsgBox(
        IntPtr hWnd, string lpText, string lpCaption, uint uType);
}
using namespace System;
using namespace System::Runtime::InteropServices;

typedef void* HWND;
[DllImport("user32", EntryPoint = "MessageBoxA")]
extern "C" int MsgBox(
    HWND hWnd, String* lpText, String* lpCaption, unsigned int uType);

另请参阅