BadImageFormatException in .net core 3.1

Issue

Loading a VC++ .Net Framework DLL (likely be the case with other C++ DLLs) in .net core 3.1 fails with System.BadImageFormatException.

Official docs

“The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.”

They list the following probable causes:

  • An assembly developed with earlier version of .net tries to load a dll developed with newer version.
  • Trying to load an un-managed dynamic link library as if it was managed.
  • You are trying to load a reference assembly in a context other than the reflection-only context.
  • A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources.
  • Platform mismatch ex: you are trying to load ARM assemblies in an x86.
  • Reflecting on C++ executable files may throw this exception. This is most likely caused by the C++ compiler stripping the relocation addresses.

Found similar issues

Suspected sources

  • ❌ Incompatibility in-between VC++ .Net Framework and .net core
  • ❌ Incompatibility in-between System.Drawing. * from the VC++ project and its .net core counter part

Actual source

The VC++ Dll had a dependency on nVida’s ONNX Runtime although all of its direct dependencies were present on of their dependencies had a different version. Reinstalling the environment resolved the issue.

Summary

If we try to load a VC++ .Net or native dll that has other native dependencies one of which is missing or has a different version than expected, we will get a System.BadImageFormatException. Be extra careful if the referenced dlls, SDK is driver dependent such as the Onnx runtime.


@Árpád Barta
Reminder for my self and maybe others about things that I have already bumped into, or just discovered ...

GitHubTwitterLinkedIn