代码之家  ›  专栏  ›  技术社区  ›  Mike_G

基于64位或32位操作系统导入外部dll

  •  8
  • Mike_G  · 技术社区  · 15 年前

    我有一个32位和64位版本的dll。我的.NET WinForm配置为“任何CPU”,我的老板不会让我们为不同的操作系统版本分别安装。所以我想知道:如果我在安装中打包这两个dll,那么有没有办法让WinForm确定它的64位/32位并加载正确的dll。

    this article 在我希望使用的方法上定义DLLImport属性的方法。有什么想法吗?

    5 回复  |  直到 15 年前
        1
  •  6
  •   Kieron    15 年前

    你能把它们都导入并决定用.NET调用哪一个吗?

    [DllImport("32bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]
    public static extern int CallMe32 (IntPtr hWnd, String text, String caption, uint type);
    
    [DllImport("64bit.dll", CharSet = CharSet.Unicode, EntryPoint="CallMe")]
    public static extern int CallMe64 (IntPtr hWnd, String text, String caption, uint type);
    
        2
  •  14
  •   Hans Passant    15 年前

    您可以利用setdlldirectoryapi函数,它可以更改非托管程序集的搜索路径。将32位DLL存储在app install目录的x86子目录中,将64位DLL存储在x64子目录中。

    using System.IO;
    using System.Reflection;
    using System.Runtime.InteropServices;
    ...
    
        public static void SetUnmanagedDllDirectory() {
            string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            path = Path.Combine(path, IntPtr.Size == 8 ? "x64 " : "x86");
            if (!SetDllDirectory(path)) throw new System.ComponentModel.Win32Exception();
        }
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool SetDllDirectory(string path);
    
        3
  •  3
  •   SLaks    15 年前

    你应该把两个不同的 extern 方法,并生成一个内部方法 IntPtr.Size

        4
  •  3
  •   Reed Copsey    15 年前

    我的解决方案是创建一个抽象类,用一个具体的版本加载和包装我的32位DLL,用一个单独的实现加载和包装64位DLL。基类中的单个工厂方法可用于基于 IntPtr.Size .

        5
  •  2
  •   Andras Vass    15 年前

    …或者你可以用 Marshal.GetDelegateForFunctionPointer() dynamic P/Invoke .
    …或者打电话 LoadLibrary() with a fully qualified path 在CLR尝试为您加载之前。