C# 检查非托管DLL是32位还是64位?

C# 检查非托管DLL是32位还是64位?,c#,dll,64-bit,32-bit,C#,Dll,64 Bit,32 Bit,如何以编程方式在C中判断非托管DLL文件是x86还是x64?请参阅。下面是一个基本实现: public static MachineType GetDllMachineType(string dllPath) { // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx // Offset to PE header is always at 0x3C. // The PE heade

如何以编程方式在C中判断非托管DLL文件是x86还是x64?

请参阅。下面是一个基本实现:

public static MachineType GetDllMachineType(string dllPath)
{
    // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
    // Offset to PE header is always at 0x3C.
    // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
    // followed by a 2-byte machine type field (see the document above for the enum).
    //
    FileStream fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    fs.Seek(0x3c, SeekOrigin.Begin);
    Int32 peOffset = br.ReadInt32();
    fs.Seek(peOffset, SeekOrigin.Begin);
    UInt32 peHead = br.ReadUInt32();

    if (peHead!=0x00004550) // "PE\0\0", little-endian
        throw new Exception("Can't find PE header");

    MachineType machineType = (MachineType) br.ReadUInt16();
    br.Close();
    fs.Close();
    return machineType;
}
MachineType
enum定义为:

public enum MachineType : ushort
{
    IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
    IMAGE_FILE_MACHINE_AM33 = 0x1d3,
    IMAGE_FILE_MACHINE_AMD64 = 0x8664,
    IMAGE_FILE_MACHINE_ARM = 0x1c0,
    IMAGE_FILE_MACHINE_EBC = 0xebc,
    IMAGE_FILE_MACHINE_I386 = 0x14c,
    IMAGE_FILE_MACHINE_IA64 = 0x200,
    IMAGE_FILE_MACHINE_M32R = 0x9041,
    IMAGE_FILE_MACHINE_MIPS16 = 0x266,
    IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
    IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
    IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
    IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
    IMAGE_FILE_MACHINE_R4000 = 0x166,
    IMAGE_FILE_MACHINE_SH3 = 0x1a2,
    IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
    IMAGE_FILE_MACHINE_SH4 = 0x1a6,
    IMAGE_FILE_MACHINE_SH5 = 0x1a8,
    IMAGE_FILE_MACHINE_THUMB = 0x1c2,
    IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
}
我只需要其中的三个,但为了完整起见,我把它们都包括进去了。最终64位检查:

// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
    switch (GetDllMachineType(dllPath))
    {
        case MachineType.IMAGE_FILE_MACHINE_AMD64:
        case MachineType.IMAGE_FILE_MACHINE_IA64:
            return true;
        case MachineType.IMAGE_FILE_MACHINE_I386:
            return false;
        default:
            return null;
    }
}

更简单的是:查看System.Reflection.Module类。它包括GetPEKind方法,该方法返回2个描述代码类型和CPU目标的枚举。别再耍花招了

(这篇内容丰富的帖子的其余部分无耻地抄袭自)

示例代码:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);
Assembly-Assembly=Assembly.reflectiononnlyloadfrom(@)

PortableExecutableKinds枚举:

ImageFileMachine枚举:

使用Visual Studio命令提示符,dumpbin/headers dllname.dll也可以工作。在我的计算机上,输出的开头说明:

FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007

不要使用
Assembly.LoadFile
,而是使用
Assembly.reflectiononnlyloadfrom
。这将使您能够解决“图像格式错误”的异常问题。

我知道更新该文件已经有一段时间了。通过将文件加载到自己的AppDomain中,我能够避免“图像格式错误”的异常

        private static (string pkName, string imName) FindPEKind(string filename)
    {
        // some files, especially if loaded into memory
        // can cause errors. Thus, load into their own appdomain
        AppDomain tempDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
        PEWorkerClass remoteWorker =
            (PEWorkerClass)tempDomain.CreateInstanceAndUnwrap(
                typeof(PEWorkerClass).Assembly.FullName,
                typeof(PEWorkerClass).FullName);

        (string pkName, string imName) = remoteWorker.TryReflectionOnlyLoadFrom_GetManagedType(filename);

        AppDomain.Unload(tempDomain);
        return (pkName, imName);
    }
此时,我将执行以下操作:

        public (string pkName, string imName) TryReflectionOnlyLoadFrom_GetManagedType(string fileName)
    {
        string pkName;
        string imName;
        try
        {
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile: fileName);
            assembly.ManifestModule.GetPEKind(
                peKind: out PortableExecutableKinds peKind,
                machine: out ImageFileMachine imageFileMachine);

            // Any CPU builds are reported as 32bit.
            // 32bit builds will have more value for PortableExecutableKinds
            if (peKind == PortableExecutableKinds.ILOnly && imageFileMachine == ImageFileMachine.I386)
            {
                pkName = "AnyCPU";
                imName = "";
            }
            else
            {
                PortableExecutableKindsNames.TryGetValue(
                    key: peKind,
                    value: out pkName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    pkName = "*** ERROR ***";
                }

                ImageFileMachineNames.TryGetValue(
                    key: imageFileMachine,
                    value: out imName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    imName = "*** ERROR ***";
                }
            }

            return (pkName, imName);
        }
        catch (Exception ex)
        {
            return (ExceptionHelper(ex), "");
        }
    }
在my Widows\Assembly目录下运行此命令,在处理3600多个文件时,不会出现任何错误。 注意:我使用字典加载返回的值


我希望它能有所帮助。YMMV

这只在您可以在流程中实际加载程序集的情况下起作用。如果机器类型和比特数不匹配,您将在assembly.LoadFile()处遇到“坏图像格式”异常,您将永远无法访问GetPEKind()我添加了FileAccess.Read到您的FileStream实例化中-否则,当试图确定C:\Windows或C:\Program FilesGetPEKind()中DLL的位时,它会让我们大吃一惊检查32位程序集时,64位进程失败。您的代码是否有效?请检查堆栈溢出问题。这是否回答了您的问题?很遗憾,在使用
程序集时,我仍然收到
系统.BadImageFormatException
。ReflectionOnlyLoadFrom