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)
13443정성태11/14/20232832개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232598개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232998닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232577Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20233190닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232810닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232960닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233197닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233097닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232918스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232575스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232663오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20233085스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232884닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233129닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233265닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233459닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233579스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233343닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233332스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233460닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233551닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235948스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233337스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20234100닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233632닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...