관리되지 않은 DLL이 32 비트 또는 64 비트인지 확인하십시오.
문제
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
열거는 다음과 같이 정의됩니다.
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,
}
나는 이것들 중 3 개만 필요했지만 완전성을 위해 모두 포함시켰다. 최종 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;
}
}
다른 팁
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
더 쉽게 : system.reflection.module 클래스를 확인하십시오. 여기에는 코드 유형과 CPU 대상을 설명하는 2 개의 열거를 반환하는 getpekind 메소드가 포함됩니다. 더 이상 16 진수!
(이 매우 유익한 게시물의 나머지 부분은 http://www.developersdex.com/vb/message.asp?p=2924&r=6413567)
샘플 코드 :
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);
휴대용 외환 신경은 어셈블리의 종류를 확인하는 데 사용될 수 있습니다. 5 가지 값이 있습니다.
Ilonly : 실행 파일에는 MSIL (Microsoft Intermediate Language) 만 포함되므로 32 비트 또는 64 비트 플랫폼과 관련하여 중립적입니다.
NOTAPORTableExecutableImage : 파일은 휴대용 실행 파일 (PE) 파일 형식이 아닙니다.
PE32PLUS : 실행 파일에는 64 비트 플랫폼이 필요합니다.
필요한32 비트 : 실행 파일은 32 비트 플랫폼 또는 64 비트 플랫폼의 WOW (Windows) 환경의 32 비트 Windows에서 실행할 수 있습니다.
Unmanaged32bit : 실행 파일에는 순수한 관리되지 않은 코드가 포함되어 있습니다.
다음은 링크입니다.
module.getPekind 메소드 :http://msdn.microsoft.com/en-us/library/system.reflection.module.getpekind.aspx
PortableExecutablekinds 열거 :http://msdn.microsoft.com/en-us/library/system.reflection.portableExecutableKinds(vs.80).aspx
ImageFileMachine 열거 :http://msdn.microsoft.com/en-us/library/system.reflection.imagefilemachine.aspx
대신에 Assembly.LoadFile
, 사용 Assembly.ReflectionOnlyLoadFrom
. 이렇게하면 "잘못된 이미지 형식"예외를 해결할 수 있습니다.
나는 이것이 업데이트 된 이래로 오랜 시간이 지났다는 것을 알고 있습니다. 파일을 자체 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), "");
}
}
내 Widows Assembly Directory에 대해 이것을 실행하면 3600 개가 넘는 파일이 처리 된 상태에서 0 오류가 발생합니다. 참고 : 사전을 사용하여 반환되는 값을로드합니다.
도움이되기를 바랍니다. ymmv