Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI/C# BadImageFormat Exception when loading form

I created a C++/CLI assembly that creates a wrapper around native C++ code. The resource compiles and the assembly loads fine into my C# project when I add it as a resource. I can access my objects and intellisense from within my application, but when attempting to build, it crashes with the exception:

BadImageFormat

Could not load file or assembly 'MyCLI, Version=1.0.3680.28432, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.

I load it into my form load event:

MyCLI.myCLI z;

... and when I compile, it crashes on this line in my main constructor in C#

Application.Run(new Form1());

Does anyone have an idea of what could be causing this exception?

Thanks

like image 367
George Johnston Avatar asked Jan 23 '23 15:01

George Johnston


1 Answers

You are trying to run this code on a 64-bit operating system. Your C# code will get nicely compiled to 64-bit machine code. But you'll hit the wall when it tries to load a 32-bit C++/CLI assembly.

In the C# project, use Project + Properties, Application tab, Platform Target = x86. Creating a 64-bit version of your C++/CLI assembly is possible too, use Build + Configuration Manager. Using Platform Target is the better solution.

like image 51
Hans Passant Avatar answered Jan 29 '23 04:01

Hans Passant