Home > Back-end >  System.BadImageFormatException when use C# call C
System.BadImageFormatException when use C# call C

Time:06-15

code is here https://github.com/Layty/cppnetdll

I have check the cpp dll and c# all is on x86, my pc is x64 ,I have also use both cpp and C# with x64 but it still tell me like

Unhandled exception. System.BadImageFormatException: Could not load file or assembly 'DLLMYX86, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. 试图加载格式不正确的程序。
File name: 'DLLMYX86, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' ---> System.BadImageFormatException: 试图加载格式不正确的程序。 (0x8007000B)
   at MYNETX86.Program.Main(String[] args)

CodePudding user response:

In .NET when you compile a managed assembly the compiler generate a intermediate code which is then compile at the fly by the JIT (just in time compiler) for the machine architecture where you are running your application.

A native (C ) dll is compiled for a specific architecture (could be x86 or x64) and the binary image file is specific for that architecture.

If you want to use a native dll from a .NET app you have to be sure that the JIT compiles the code for the same architecture the native dll was made for. The only way to be sure that everything is coherent is to compile the .NET assembly for that specific architecture. In Visual Studio this is possible switching the target architecture from Any CPU to the same of the native dll.

CodePudding user response:

Your native dll is referenced as a regular managed dll. This will not work. Your options are

  1. Rewrite the functionality in managed code
  2. Use C /CLI to produce a managed dll
  3. Use PInvoke to call a native dll

I would prefer option 1 if possible. Interacting with unmanaged code is kind of a pain in the ass for anything except the most trivial signatures.

CodePudding user response:

Your C# project targets .Net Core 3.1, so you need update your C project to target the same version.

In Project Properties > Advanced > C /CLI Properties.

  1. Set Common Language Runtime Support to .Net Core Runtime Support (/clr:netcore), then click Apply.

  2. Set .Net Target Framework Version to netcoreapp3.1 or .NET Core 3.1.

CodePudding user response:

I have solve this problem. I remove the pch.h and the pch.cpp and dllmain , then every thing run well .

But I dont know why ? it is just pre combile , and I have clean obj dir and clean project befor .

CodePudding user response:

I have update my git code . just fix https://github.com/Layty/cppnetdll/blob/master/DLLMYX86/DLLMYX86/dllmain.cpp or del this file.

I have make other both include cpp and C# .

othrs if have problem can download it. it works well

now I can new cpp object in c#

  • Related