试图加载格式不正确的程序

本文关键字:程序 不正确 格式 加载 | 更新日期: 2023-09-27 18:09:10

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

这个问题解释了如何在编译时选择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 <exeName>.MiniDumpMethods.MiniDumpWriteDumpX86(IntPtr hProcess, UInt32 processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam)

任何想法我可以有条件地加载无论是x86或x64版本的dll?

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

谢谢

试图加载格式不正确的程序

您的程序将是32位或64位。不可能在64位程序中执行32位代码,也不可能在32位程序中执行64位代码。如果您尝试的话,将会得到一个运行时异常!因此,不能让一个程序同时执行x86和x64代码。你有三个选择,这取决于你想做什么。

选项1:(原始答案)

使用"Any CPU",那么你的程序可以在32位平台上以32位运行,在64位平台上以64位运行。在这种情况下,您可以使用此代码来确定使用哪个DLL,您只需要一个程序集就可以处理32位和64位平台,并且它将使用正确的DLL:

使用Environment.Is64BitProcess

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

选项2:

如果你想使用"预处理器"条件来做这件事,那么你将编译两个不同的程序集。您可以编译使用32位DLL的32位程序集以在32位平台上运行,并且可以编译单独的64位程序集以在64位平台上运行。

选项3:

使用IPC (Inter-process-communications)。您将有一个64位程序"连接"到一个32位程序。64位程序可以运行64位DLL函数,但是当您需要运行32位DLL函数时,您必须向32位程序发送包含运行它所需信息的消息,然后32位程序可以发送包含您想要返回的任何信息的响应。