【问题标题】:How load the Dll according to platform如何根据平台加载DLL
【发布时间】:2011-12-23 11:55:57
【问题描述】:

我有一个 32 位和 64 位的 dll,现在我希望我的 exe 根据解决方案平台调用 dll,这意味着当设置 x64 时,将调用 64 位的 dll。为此,我声明了一个函数 GetPlatform()。

Public Function GetPlateform() As String

    Dim var1 As String
    If (IntPtr.Size = 8) Then
        var1 = hellox64
    Else
        var1 = hello
    End If
    Return var1
End Function

当表单加载时 这个 var1 被分配给 var 和 finally。

Public Declare Function function1 Lib "var" (ByVal Id As Integer) As Integer

但是当我调试代码“DllNotFoundException”时出现。 注意:该 dll 在 vc++ 中。

【问题讨论】:

  • 只用一个名字安装正确的DLL!!!!创建 2 个安装包
  • 但是@Martin 这可能吗?

标签: vb.net visual-c++ dll dllnotfoundexception


【解决方案1】:

将您的本机 dll 存储到子文件夹中,并通过使用要加载的正确版本的路径相应地填充 PATH 进程环境变量来提示 Library Loader

例如,给定这个树形布局...

Your_assembly.dll
  |_NativeBinaries
      |_x86
          |_your_native.dll
      |_amd64
          |_your_native.dll

...还有这段代码(抱歉,C#,没有 VB.Net :-/)...

internal static class NativeMethods
{
    private const string nativeName = "your_native";

    static NativeMethods()
    {
        string originalAssemblypath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;

        string currentArchSubPath = "NativeBinaries/x86";

        // Is this a 64 bits process?
        if (IntPtr.Size == 8)
        {
            currentArchSubPath = "NativeBinaries/amd64";
        }

        string path = Path.Combine(Path.GetDirectoryName(originalAssemblypath), currentArchSubPath);

        const string pathEnvVariable = "PATH";
        Environment.SetEnvironmentVariable(pathEnvVariable,
            String.Format("{0}{1}{2}", path, Path.PathSeparator, Environment.GetEnvironmentVariable(pathEnvVariable)));
    }

    [DllImport(nativeName)]
    public static extern int function1(int param);

    [DllImport(nativeName)]
    public static extern int function2(int param);
}

...function1function2 将动态绑定到本机代码的 32 位或 64 位版本,具体取决于 IntPtr 的大小(更多信息请参阅 @987654322 的这篇文章@ 或这个 StackOverflow question)。

注意 1: 当两个版本的 dll 具有相同的名称或您不愿意复制每个外部引用时,此解决方案特别有用。

注意2:这已经在LibGit2Sharp中成功实现。

【讨论】:

    【解决方案2】:

    不,您不能在 lib 语句中动态创建对 DLL 的引用。但是,您可能(免责声明:尚未尝试)能够创建两个引用并在您的代码中调用相应的引用。

    Public Declare Function Function132 Lib "My32BitLib.DLL" Alias "function1" (ByVal Id As Integer) As Integer
    
    Public Declare Function Function164 Lib "My64BitLib.DLL" Alias "function1" (ByVal Id As Integer) As Integer
    

    然后您需要在平台上进行分支并根据平台调用适当的别名函数名称(Function132 或 Function164)。

    【讨论】:

    • 交换你的函数名和别名。你想要Declare Function function164 ... Alias "Function1"
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 2021-01-28
    • 2012-12-12
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多