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)
13608정성태4/26/2024413닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024412닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024421닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024641닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024669오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024866닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024929닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024961닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024972닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024936닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024977닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024971닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241078닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241066닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241081닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241090닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241081Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241274닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241360오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241532Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241497Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241455개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...