Search code examples
dllreferenceclrref.net-5

C# CLR Excecption "BadImageFormatException: Could not load file or assembly"


I am using VS 2019 Version 16.8.2 enter image description here

I referred a "CLR Class Library(.NET Core)" project in my "WPF App (.NET)" project and i met a exception:

BadImageFormatException: Could not load file or assembly 'LibCLR, Version=1.0.7646.21580, Culture=neutral, PublicKeyToken=null'. An attempt was made to load a program with an incorrect format.

Let me first talk about how I did it.

  1. Create a "WPF App (.NET)" project "TestCLR" enter image description here

  2. Add a new "CLR Class Library(.NET Core)" project "LibCLR" in this solution enter image description here

  3. The "common language runtime support" setting of "LibCLR" enter image description here

  4. Target "TestCLR" to ".NET 5.0" enter image description here

  5. "LibCLR.h" created automatically in project "LibCLR" and codes was inside

#pragma once

using namespace System;

namespace LibCLR {
    public ref class Class1
    {
        // TODO: Add your methods for this class here.
    };
}
  1. Add "new LibCLR.Class1();" in MainWindow.xaml.cs in project "TestCLR"
using System.Windows;

namespace TestCLR {
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
            new LibCLR.Class1();
        }
    }
}
  1. Rebuild All and debug, then i met exception enter image description here

  2. Then i change the solution platform to x64 or x84, the exception were the same. enter image description here

  3. It works well if i choice "WPF App (.NET Framework)" for "TestCLR" in step 1 and "CLR Class Library(.NET Framework)" for "LibCLR" in step 2

Why did not it work? Can not i use a "CLR Class Library(.NET)" project as a project reference in a "WPF App (.NET Core)" project? How can i solve this problem?


Solution

  • You should change Platform target to "X86" here enter image description here