使用Environment.Is64BitProcess从c#应用程序动态调用32位或64位DLL

Bri*_*ley 4 c# .net-4.0

我正在开发一个用 C# 编写的 .NET 4.0 项目(通过 Visual Studio 2010)。有一个需要使用 C/C++ DLL 的第 3 方工具,并且有 C# 中的 32 位应用程序和 64 位应用程序的示例。

问题是 32 位演示静态链接到 32 位 DLL,而 64 位演示静态链接到 64 位 DLL。作为一个 .NET 应用程序,它可以作为 32 位或 64 位进程在客户端 PC 上运行。

.NET 4.0 框架提供了Environment.Is64BitProcess 属性,如果应用程序作为64 位进程运行,该属性将返回true。

我想做的是在检查 Is64BitProcess 属性后动态加载正确的 DLL。然而,当我研究动态加载库时,我总是会想到以下内容:

[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);

[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
Run Code Online (Sandbox Code Playgroud)

看来这些方法是专门针对 32 位操作系统的。有 64 位等效项吗?

只要基于 Is64BitProcess 检查调用适当的方法,静态链接 32 位和 64 位库是否会导致问题?

public class key32
{
    [DllImport("KEYDLL32.DLL", CharSet = CharSet.Auto)]
    private static extern uint KFUNC(int arg1, int arg2, int arg3, int arg4);

    public static bool IsValid()
    {
       ... calls KFUNC() ...
    }
}

public class key64
{
    [DllImport("KEYDLL64.DLL", CharSet = CharSet.Auto)]
    private static extern uint KFUNC(int arg1, int arg2, int arg3, int arg4);

    public static bool IsValid()
    {
       ... calls KFUNC() ...
    }
}
Run Code Online (Sandbox Code Playgroud)

...

if (Environment.Is64BitProcess)
{
    Key64.IsValid();
}
else
{
    Key32.IsValid();
}
Run Code Online (Sandbox Code Playgroud)

谢谢你!!

Han*_*ant 5

有很多方法可以做到这一点:

  • 这是一个部署问题,只需获取安装程序复制的正确 DLL,给它们提供相同的名称

  • 很少有程序实际上需要 64 位代码提供的大量地址空间。只需将平台目标设置为 x86

  • 使用 [DllImport] 属性的 EntryPoint 字段。将其设置为“KFUNC”。并给这些方法赋予不同的名称。现在您可以根据 IntPtr.Size 的值调用其中之一

演示最后一个解决方案:

[DllImport("KEYDLL32.DLL", EntryPoint = "KFUNC")]
private static extern uint KFUNC32(int arg1, int arg2, int arg3, int arg4);

[DllImport("KEYDLL64.DLL", EntryPoint = "KFUNC")]
private static extern uint KFUNC64(int arg1, int arg2, int arg3, int arg4);

...

if (IntPtr.Size == 8) KFUNC64(1, 2, 3, 4);
else                  KFUNC32(1, 2, 3, 4);
Run Code Online (Sandbox Code Playgroud)