在64位进程中加载32位dll

3

我希望我的C#应用程序可以有条件地运行本地方法,可以选择运行dll的x86或x64版本。每当我尝试加载32位dll时,就会出现以下错误:

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)
背景: 我希望我的二进制文件可以对给定进程进行内存转储。根据正在进行内存转储的进程是32位还是64位,它将选择从x86或x64版本的dbghelp.dll运行MiniDumpwriteDump方法。

我目前正在执行以下操作:

[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或x64版本的dll吗?
(注意:dbghelpx86.dll是我重命名的dbghelp.dll的x86版本)
谢谢

你可以检查IntPtr.Size是否为4或8来判断主机操作系统是32位还是64位。 - Matias Cicero
@MatiCicero 这与主机操作系统无关。决策需要根据每个进程进行。 - Zain Rizvi
1个回答

5

在64位进程中无法加载32位DLL。为支持这种情况,您需要有两个不同的EXE文件,一个编译为64位,另一个编译为32位。

如果您运行64位进程并遇到32位转储,则必须启动32位版本的EXE来处理转储文件。一旦处理完成,您可以使用某种IPC(进程间通信)机制将结果发送回64位进程。


我找到了一种加载它的方法。https://www.codeproject.com/Articles/5336312/Load-a-x86-DLL-into-a-x64-executable-mission-possi。虽然还没有完成,但从技术上讲是可行的。 - Michael Chourdakis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接