Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Cocowalla Avatar asked Nov 08 '19 10:11

Cocowalla


2 Answers

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!

like image 161
Cocowalla Avatar answered Nov 03 '22 07:11

Cocowalla


I am using .net 5.0 as the CLI runtime. I finally found that the problem I have is missing native dependency DLLs.

For native applications, there will be an error prompt telling you which DLL is missing. While in .net core C++/CLI, they only give you a BadImageFormatException.

My solution is, create a pure native console project, paste the code that will cause BadImageFormatException, run it and see which DLL is missing then add it back to C++/CLI project file list.

I just found some unexpected dependencies.

like image 1
kana Avatar answered Nov 03 '22 06:11

kana