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)
13545정성태1/30/20242148닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20242177오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242212Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242235오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242329VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242475Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242432개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242545닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242653닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242684닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242589닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242357닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242547닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242456닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242431닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242286닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242187닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242336Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242257오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242338닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242291오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242367오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242170오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242302닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242381닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242172오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...