2

我有一个 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 最后。

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

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

4

2 回答 2

3

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

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

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);
}

...function1并且function2将动态绑定到本机代码的 32 位或 64 位版本,具体取决于 IntPtr 的大小(更多内容请参见Scott Hanselman的这篇文章或这个StackOverflow 问题)。

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

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

于 2011-11-30T16:01:08.033 回答
1

不,您不能在 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)。

于 2011-11-07T17:41:59.487 回答