如何在运行时选择具有相同 API 的两个 dll 之一



我有两个具有相同API的dll访问不同的硬件设备(由我构建(。我想根据在计算机中检测到的硬件在运行时选择其中一个。

我发现我可以在从 DLL 调用任何函数之前使用 windows 函数LoadLibrary加载两个库之一,VB 将使用加载的库 - 但这仅在文件名与函数Declare(或Dllimport(中的内容匹配时才有效,即两个 dll 版本必须具有相同的文件名。这意味着 dll 不能位于同一目录中(例如在 System32 目录中(。

我是否可以有两个具有两个不同文件名的 dll,为运行时可选择 VB.NET 提供相同的 API?

除了使用编译常量之外,您实际上无法执行条件导入。但是,您可以导入两个dll并创建一个方法,根据您的条件调用任何一个。

像这样:

<DllImport("firstversion.dll", EntryPoint:="GetDevice")> _
Public Shared Function GetDevice_v1(ByVal arg1 As IntPtr, ByVal arg2 As String) As IntPtr
End Function
<DllImport("secondversion.dll", EntryPoint:="GetDevice")> _
Public Shared Function GetDevice_v2(ByVal arg1 As IntPtr, ByVal arg2 As String) As IntPtr
End Function
Public Shared Function GetDevice(ByVal arg1 As IntPtr, ByVal arg2 As String) As IntPtr
    If condition Then
        Return GetDevice_v1(arg1, arg2)
    Else
        Return GetDevice_v2(arg1, arg2)
    End If
End Function

相关内容