Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

.NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException

오랜만에 테스트 삼아 비주얼 스튜디오에서 .NET Framework 3.5 프로젝트를 만들고 "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscoree.tlb"를 참조해 실행했더니 이런 예외가 발생합니다. (또는, 참조 없이 사용하는 것도 가능합니다.)

Server Error in '/' Application.
Could not load file or assembly 'Interop.mscoree' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly 'Interop.mscoree' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'Interop.mscoree' could not be loaded.

=== Pre-bind state information ===
LOG: User = testusr10\testusr
LOG: DisplayName = Interop.mscoree
 (Partial)
LOG: Appbase = file:///C:/temp/ConsoleApp1/WebApplication1/
LOG: Initial PrivatePath = C:\temp\ConsoleApp1\WebApplication1\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\temp\ConsoleApp1\WebApplication1\web.config
LOG: Using host configuration file: C:\Users\testusr\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/testusr/AppData/Local/Temp/Temporary ASP.NET Files/root/2dbd3481/142dce22/Interop.mscoree.DLL.
LOG: Attempting download of new URL file:///C:/Users/testusr/AppData/Local/Temp/Temporary ASP.NET Files/root/2dbd3481/142dce22/Interop.mscoree/Interop.mscoree.DLL.
LOG: Attempting download of new URL file:///C:/temp/ConsoleApp1/WebApplication1/bin/Interop.mscoree.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8013101b). Probing terminated.

Stack Trace:

[BadImageFormatException: Could not load file or assembly 'Interop.mscoree' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
   System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +416
   System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +166
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +190

[ConfigurationErrorsException: Could not load file or assembly 'Interop.mscoree' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11347592
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +388
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +232
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +48
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +210
   System.Web.Compilation.WebDirectoryBatchCompiler..ctor(VirtualDirectory vdir) +191
   System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory vdir, Boolean ignoreErrors) +54
   System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +295
   System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +476
   System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +116
   System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +175
   System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert) +52
   System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +50
   System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +425
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +263

Version Information: Microsoft .NET Framework Version:2.0.50727.9174; ASP.NET Version:2.0.50727.9175

에러 메시지에는 분명히 "System.BadImageFormatException: Could not load file or assembly 'Interop.mscoree' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded."라고 원인을 친절하게 설명하고 있지만, 저는 분명히 CLR 2 버전의 x64 mscoree.tlb를 참조했는데... 뭐가 문제라는 걸까요? ^^;

우선, 원인 파악을 위해 비주얼 스튜디오가 (mscoree.tlb 참조 시 자동으로) 생성한 Interop.mscoree.dll 파일을 역어셈블러를 통해 확인해 봤습니다.

// Interop.mscoree, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null

// Global type: <Module>
// Architecture: AnyCPU (64-bit preferred)
// Runtime: .NET Framework 4
// Timestamp: 65DD458F (2/26/2024 21:14:39 AM)

그러니까... 분명히 CLR 2 x64 mscoree 어셈블리는 맞는데, 비주얼 스튜디오가 생성한 interop DLL은 ".NET Framework 4"용으로 출력이 된 것입니다. 다시 말해, 비주얼 스튜디오는 .NET Framework 4용의 tlbimp.exe를 사용해 interop DLL을 생성했던 것입니다.

그렇다면 .NET Framework 2.0용의 tlbimp.exe를 구해야 하는데요, 이게 ^^; 근래의 Windows SDK (예를 들어 Windows 10 SDK)에는 포함돼 있지 않습니다. 어쩔 수 없습니다. Windows 7 SDK를 일부러 설치하거나, 혹은 설치돼 있는 PC에서 "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin" 경로에 있는 tlbimp.exe 파일을 복사해 다음과 같이 실행해 주면 됩니다.

c:\temp> tlbimp "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscoree.tlb" /out:Interop.mscoree.dll
Microsoft (R) .NET Framework Type Library to Assembly Converter 3.5.30729.1
Copyright (C) Microsoft Corporation.  All rights reserved.

TlbImp : warning TI0000 : Importing a type library into a platform agnostic assembly.  This can cause errors if the type library is not truly platform agnostic.
TlbImp : warning TI0000 : At least one of the arguments for 'CorRuntimeHost.SwitchOutLogicalThreadState' cannot be marshaled by the runtime marshaler.  Such arguments will therefore be passed as a pointer and may require unsafe code to manipulate.
TlbImp : warning TI0000 : At least one of the arguments for 'ICorRuntimeHost.SwitchOutLogicalThreadState' cannot be marshaled by the runtime marshaler.  Such arguments will therefore be passed as a pointer and may require unsafe code to manipulate.
TlbImp : warning TI0000 : The type library importer could not convert the signature for the member 'tag_VerError.item1_data'.
TlbImp : warning TI0000 : The type library importer could not convert the signature for the member 'tag_VerError.item2_data'.
Type library imported to C:\temp\Interop.mscoree.dll

이렇게 생성한 dll 파일을 역어셈블러로 확인하면 이런 정보가 나옵니다.

// mscoree.dll

// Global type: <Module>
// Architecture: AnyCPU (64-bit preferred)
// Runtime: .NET Framework 2.0
// Timestamp: 65DD764B (2/26/2024 21:42:35 PM)

끝이군요, 이제 ^^ 기존 프로젝트에서 참조한 "mscoree" 항목을 삭제하고 위의 명령어로 생성한 "Interop.mscoree.dll" 파일을 직접 참조하면 됩니다.

(첨부 파일은 위의 방법으로 생성한 "Interop.mscoree.dll"입니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/27/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13587정성태3/27/20241403오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241639Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241503Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241470개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241506Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241631Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241779개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241315닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241517오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241682닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241951닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241600닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241710닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241615닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241581닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241676닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241652닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241663닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241587닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241805닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241808오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241826오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241687닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241925Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241954디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241984오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...