DllImport – 尝试加载格式不正确的程序

我希望我的C#应用​​程序有条件地运行本机方法。 在运行时决定是运行dll的x86还是x64版本。

这个问题解释了如何在编译时选择32位或64位,但这没有帮助。 我想在运行时做出决定。

我目前正在做以下事情:

[SuppressUnmanagedCodeSecurity] internal static class MiniDumpMethods { [DllImport("dbghelp.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool MiniDumpWriteDump( IntPtr hProcess, uint processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam); [DllImport("dbghelpx86.dll", EntryPoint = "MiniDumpWriteDump", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool MiniDumpWriteDumpX86( IntPtr hProcess, uint processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam); } 

但是当我尝试调用x86方法时,我得到错误:

 Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) at .MiniDumpMethods.MiniDumpWriteDumpX86(IntPtr hProcess, UInt32 processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam) 

知道如何有条件地加载dll的x86或x64版本吗?

(注意:dbghelpx86.dll是我重命名的dbghelp.dll的x86版本)

谢谢

您的程序将是32位或64位。 在64位程序中无法执行32位代码,并且无法在32位程序中执行64位代码。 如果你尝试,你会得到一个运行时exception! 因此,您不能拥有一个同时执行x86和x64代码的程序。 您有3个选项,具体取决于您想要做什么。

选项1 :(原始答案)

使用“任何CPU”,然后您的程序可以在32位平台上以32位运行,在64位平台上以64位运行。 在这种情况下,您可以使用此代码来确定要使用的DLL,并且您只需要1个程序集就能够处理32位和64位平台,它将使用正确的dll:

使用Environment.Is64BitProcess

 if (Environment.Is64BitProcess) { //call MiniDumpWriteDump } else { //call MiniDumpWriteDumpX86 } 

选项2:

如果要使用“预处理器”条件来执行此操作,则可以编译2个不同的程序集。 您将编译一个32位程序集以在使用32位DLL的32位平台上运行,并且您将编译一个单独的64位程序集以在64位平台中运行。

选项3:

使用IPC(进程间通信)。 你将有一个64位程序“连接”到32位程序。 64位程序可以运行64位DLL函数,但是当您需要运行32位DLL函数时,您必须向32位程序发送一条消息,其中包含运行它所需的信息,然后32位程序可以发送包含您想要的任何信息的响应。