Search code examples
c++.net.net-coremanaged-c++.net-core-3.0

Bad image format when running managed C++/CLI assembly in .NET Core 3.1


I was super excited to see that the latest previews of .NET Core 3.1 and Visual Studio 2019 add support for managed C++/CLI projects, as such a project is the only think keeping a particular project on .NET Framework.

So, I installed Visual Studio Preview 16.4.0 Preview 4, along with the "C++/CLI support for v142..." options, and as expected I see the new C++ CLR templates and have .NET Core 3.1 preview 2 installed

I created a new project using the "CLR Class Library (.NET Core)" template, copied the files an old managed C++/CLI project, tweaked a little, and the assembly built - great!

However, when I try to use the assembly in a .NET Core 3.1, I get this fatal exception:

Unhandled exception. System.BadImageFormatException: Could not load file or assembly 'MyAssembly, Version=2019.0.1.0, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.
File name: 'MyAssembly, Version=2019.0.1.0, Culture=neutral, PublicKeyToken=null'
   at TestApp.Program.Main(String[] args)

Both the managed assembly and test app target X64. Any ideas what could be the problem?


Solution

  • Someone from Microsoft provided the solution over on the Github repo.

    When the managed C++/CLI project is built, a file ijwhost.dll is placed in the output folder alongside the assembly - this file needs to be deployed with the app that uses the assembly.

    After putting ijwhost.dll in the same folder as the app, it worked as expected.

    As an aside, the old C++/CLI project that I built against .NET Core 3.1 preview is actually quite complex - I'm very pleasantly surprised that it basically "just worked"!

    Hopefully a better error message will be used in future!