Skip to content

BadImageFormatException when loading C++/CLI DLLs in Core 3.1 #31743

Open

Description

@Farengeto

Operating System Version: Azure virtual machine with a Windows 10 Pro, Version 1809 base
.NET Core Version: 3.1
Visual Studio Version: 16.4.3 and 16.4.4

Whenever I attempt to access a C++/CLI project (targeted for .NET Core 3.1) from a C# project, the execution will immediately crash when attempting to load the assembly.

I have managed to reproduce this error in multiple independent solutions, on multiple computers, so it does not appear to be tied to a code- or computer-specific issue on my end.

If the project is executed in Visual Studio with the debugger, the debugger itself appears crash upon reaching the method which calls the C++/CLI DLL. No information will be provided in Debug other than these lines:

The program '[13640] NET Core CLI Test.exe: Program Trace' has exited with code 0 (0x0).
The program '[13640] NET Core CLI Test.exe' has exited with code -529697949 (0xe06d7363) 'Microsoft C++ Exception'.

As a curious note, the debugger also skips over the calling method if I attempt to step into it, reporting it as "non-user code".

If executed without a debugger, more information is provided when the crash occurs:

Unhandled exception. System.BadImageFormatException: Could not load file or assembly 'Mock CLI Project, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.
File name: 'Mock CLI Project, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
at NET_Core_CLI_Test.Program.CallingMethod(Int32 a, Int32 b)
at NET_Core_CLI_Test.Program.Main(String[] args) in C:\Users\travis.ridge\source\repos\NET Core CLI Test\NET Core CLI Test\Program.cs:line 11

In both situations, an error will be added to the Windows event log, displaying the same basic information each time.

Faulting application name: NET Core CLI Test.exe, version: 1.0.0.0, time stamp: 0x5dedc13b
Faulting module name: KERNELBASE.dll, version: 10.0.17763.914, time stamp: 0xfb6790ac
Exception code: 0xe0434352
Fault offset: 0x0000000000039159
Faulting process id: 0x31e0
Faulting application start time: 0x01d5d8549d80476e
Faulting application path: C:\Users\travis.ridge\source\repos\NET Core CLI Test\NET Core CLI Test\bin\x64\Debug\netcoreapp3.1\NET Core CLI Test.exe
Faulting module path: C:\windows\System32\KERNELBASE.dll
Report Id: 575a2b9a-1f69-4d48-8d07-ac8dfe6917d4
Faulting package full name:
Faulting package-relative application ID:

Below I've included the code example from a minimal solution in Visual Studio with which I am able to consistently reproduce this issue.

Example C# script. The program crashes when CallingMethod() is invoked.

using CLI;

namespace NET_Core_CLI_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2;
            int b = 2;
            int sum = CallingMethod(a, b); //Crash occurs when executing this line
        }

        static int CallingMethod(int a, int b)
        {
            //Execution never reaches here
            MockWrapper wrapper = new MockWrapper();
            return wrapper.Add(a, b);
        }
    }
}

The ModelWrapper.cpp class:

#pragma once
#include "pch.h"
#include "MockWrapper.h"

#include <exception>

using namespace System;
using namespace System::Runtime::InteropServices;

namespace CLI {
	MockWrapper::MockWrapper() {

	}

	int MockWrapper::Add(int a, int b) {
		return a + b;
	}
}

I can provide further information upon request.

Activity

  1. scalablecory commented on Feb 4, 2020

    @scalablecory
    Contributor
  2. transferred this issue fromdotnet/coreon Feb 4, 2020
  3. scalablecory commented on Feb 4, 2020

    @scalablecory
    Contributor

    Are you trying to load a 64-bit DLL inside a 32-bit process, or vice-versa?

  4. vcsjones commented on Feb 4, 2020

    @vcsjones
    Member

    Perhaps related to #521.

  5. Farengeto commented on Feb 4, 2020

    @Farengeto
    Author

    Are you trying to load a 64-bit DLL inside a 32-bit process, or vice-versa?

    In my solutions all projects were being built in the 64-bit configuration.

    I've rechecked the test solution just to be sure: the C# project was set for x64 platform target, and the reference to the C++ project points to the x64 build. However the error persists.

  6. jeffschwMSFT commented on Feb 4, 2020

    @jeffschwMSFT
    Member
  7. jkoritzinsky commented on Feb 4, 2020

    @jkoritzinsky
    Member

    @travisridge do you have the ijwhost.dll deployed next to your C++/CLI assembly and are all of your native dependencies resolved/resolvable? Sometimes people miss that file when copying their outputs around.

    Our diagnostics for mixed-mode assembly loading need a bit of work since they throw a BadImageFormatException for basically every failure.

  8. Farengeto commented on Feb 5, 2020

    @Farengeto
    Author

    @travisridge do you have the ijwhost.dll deployed next to your C++/CLI assembly and are all of your native dependencies resolved/resolvable? Sometimes people miss that file when copying their outputs around.

    Our diagnostics for mixed-mode assembly loading need a bit of work since they throw a BadImageFormatException for basically every failure.

    @jkoritzinsky The "Ijwhost.dll" was added automatically in the folder next to the assembly in both the builds for the C++ and C# projects. (Curiously the dll had used an uppercase "i", but I tried changing it to lowercase on a hunch with no difference in error message.)

    As for the others, I'm not sure how I can verify that. I've adjusted my test project's code to remove those unnecessary includes, so at this point the only explicit external references are those in the automatically generated code (namely the "framework.h" and its reference to "windows.h").

  9. added
    questionAnswer questions and provide assistance, not an issue with source code or documentation.
    and removed
    untriagedNew issue has not been triaged by the area owner
    on Apr 3, 2020
  10. added this to the Future milestone on Apr 3, 2020
  11. nefen commented on Apr 30, 2020

    @nefen

    I face exactly the same issue with @travisridge.
    Native dll=>C++/CLI Wrapper=>aspnet core 3.1 Razor Pages Project.
    Compiles. Run breaks with BadImageFormat. Debugging breaks too.
    I checked all involved dll's with dumpbin and all were built against x64.
    Any New?

  12. msedi commented on May 6, 2020

    @msedi

    The same happens from our side, is there any news?

  13. 15 remaining items

  14. Weijee commented on May 6, 2021

    @Weijee

    I have tested this issue on .NETCore3.1/.NET5 by using ConsoleApp/WebApplication/WebApi, and the result goes like this:

    Reference ConsoleApp WebApplication WebApi
    Reference C++/CLI Project OK OK OK
    Reference C++/CLI Dll NG NG NG

    NG: BadImageFormatException occurs
    I dont know what is the defference between these two reference modes.
    Any ideas?

  15. ryangle commented on May 20, 2021

    @ryangle

    I have tested this issue on .NETCore3.1/.NET5 by using ConsoleApp/WebApplication/WebApi, and the result goes like this:

    Reference ConsoleApp WebApplication WebApi
    Reference C++/CLI Project OK OK OK
    Reference C++/CLI Dll NG NG NG
    NG: BadImageFormatException occurs
    I dont know what is the defference between these two reference modes.
    Any ideas?

    Check the "Copy C++ Runtime to OutDir" in the C++/Cli project.

  16. intellild commented on Jun 29, 2021

    @intellild

    Same issue
    My C# XAML application referencing my empty proxy c++/cli project works fine
    But when I reference the native c++ DLL in the proxy project, the error occurs

  17. Gornhoth commented on Jul 1, 2021

    @Gornhoth

    Similar issue with a .NET 5.0 project that references a C++ dll. All dlls are copied into the output directory when compiling, all of them and the project itself are targeting x64. When running the executable: "Unhandled exception. System.BadImageFormatException: Could not load file or assembly '...'. An attempt was made to load a program with an incorrect format." I tried the same in a .NET Framework 4.7.2 project and there it loads all assemblies properly and runs without an issue. Any idea?

  18. emanuel-v-r commented on Jul 1, 2021

    @emanuel-v-r

    @Gornhoth this comment dotnet/core#3927 (comment) may be helpful for you, it's an ugly solution but at least it worked, it was for .NET Core 3.1, but I am guessing it will work for .NET 5

  19. Gornhoth commented on Jul 1, 2021

    @Gornhoth

    @imaramos thank you for the suggestion. I searched a bit more and found https://docs.microsoft.com/en-us/dotnet/standard/analyzers/portability-analyzer which i used to see if there were any compatibility issues between the managed c++ dlls targeting .net framework 4.7.2 (as seen in assembly explorer) and my .net 5.0 project which references them. Turns out there are several incompatibilities in some dlls which prevents me from using them.

  20. FanjingLiu commented on Dec 16, 2021

    @FanjingLiu

    Same thing for me too, .Net5 console app referencing a c++cli dll, portability analyzer is all green.

  21. HengzheLi commented on Dec 17, 2021

    @HengzheLi

    Same issue when debug .net 5 app from Visualstudio. But when I build the project using MSBuild outside the VS. The app can run smoothly.

    It is strange. When I change "Use Debug Libraries" from Yes to No. All works. But this setting always work before I upgrade VS2019 to 16.11. But the source code could not be step into in this way.

  22. fiercekittenz commented on Feb 5, 2022

    @fiercekittenz

    I'm experiencing this now with a x64 net5.0-windows C# application referencing a /clr:netcore (net5.0) library. Any time the code is used from the referenced CLR project, it crashes with this same exception.

  23. kaba2 commented on Apr 4, 2022

    @kaba2

    I had a similar problem with BadImageFormatException using a C++/CLI library from C# (although with NET Framework).

    The solution was to disable "Prefer 32 bits" from the C# library properties.

  24. pawan-vinove commented on Jan 5, 2023

    @pawan-vinove

    When I had a similar problem with a C# WinForms app (.NET Core 3.1) referencing a C++/CLI .NET Core assembly, it turned out that my Visual Studio configurations were set to always build the C# project as Any CPU, regardless of the active solution platform. I added x86 and x64 platforms to my C# project and set the solution platforms to use them, and it seems OK now.

    This is not working in my case. Code is running on x86 but not able to run it on docker..

  25. dotnet-policy-service commented on Apr 15, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @agocke, @elinor-fung
    See info in area-owners.md if you want to be subscribed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-AssemblyLoaderquestionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    • Status
      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions