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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12940정성태1/26/20226863오류 유형: 789. AKS에서 hpa에 따른 autoscale 기능이 동작하지 않는다면?
12939정성태1/25/20227567.NET Framework: 1140. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP3 오디오 파일 인코딩/디코딩하는 예제파일 다운로드1
12938정성태1/24/20229951개발 환경 구성: 633. Docker Desktop + k8s 환경에서 local 이미지를 사용하는 방법
12937정성태1/24/20227780.NET Framework: 1139. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 오디오(mp2) 인코딩하는 예제(encode_audio.c) [2]파일 다운로드1
12936정성태1/22/20227694.NET Framework: 1138. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 멀티미디어 파일의 메타데이터를 보여주는 예제(metadata.c)파일 다운로드1
12935정성태1/22/20227925.NET Framework: 1137. ffmpeg의 파일 해시 예제(ffhash.c)를 C#으로 포팅파일 다운로드1
12934정성태1/22/20227494오류 유형: 788. Warning C6262 Function uses '65564' bytes of stack: exceeds /analyze:stacksize '16384'. Consider moving some data to heap. [2]
12933정성태1/21/20228029.NET Framework: 1136. C# - ffmpeg(FFmpeg.AutoGen)를 이용해 MP2 오디오 파일 디코딩 예제(decode_audio.c)파일 다운로드1
12932정성태1/20/20228467.NET Framework: 1135. C# - ffmpeg(FFmpeg.AutoGen)로 하드웨어 가속기를 이용한 비디오 디코딩 예제(hw_decode.c) [2]파일 다운로드1
12931정성태1/20/20226522개발 환경 구성: 632. ASP.NET Core 프로젝트를 AKS/k8s에 올리는 과정
12930정성태1/19/20227228개발 환경 구성: 631. AKS/k8s의 Volume에 파일 복사하는 방법
12929정성태1/19/20227018개발 환경 구성: 630. AKS/k8s의 Pod에 Volume 연결하는 방법
12928정성태1/18/20227135개발 환경 구성: 629. AKS/Kubernetes에서 호스팅 중인 pod에 shell(/bin/bash)로 진입하는 방법
12927정성태1/18/20226921개발 환경 구성: 628. AKS 환경에 응용 프로그램 배포 방법
12926정성태1/17/20227443오류 유형: 787. AKS - pod 배포 시 ErrImagePull/ImagePullBackOff 오류
12925정성태1/17/20227500개발 환경 구성: 627. AKS의 준비 단계 - ACR(Azure Container Registry)에 docker 이미지 배포
12924정성태1/15/20229015.NET Framework: 1134. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) [2]파일 다운로드1
12923정성태1/15/20227880개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226969개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225876개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226646오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226488Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226716Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225909오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225676오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225977오류 유형: 783. Visual Studio - We didn't find any interpreters
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...