Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++/CLI targetting .NET Core 3.1

.NET Core 3.1 added support for C++/CLI (Announcing .NET Core 3.1). The official announcement lists two new project templates, CLR Class Library (.NET Core) and CLR Empty Project (.NET Core), which we can indeed find and use.

However, there is no additional information about supporting technologies such as WPF or Windows Forms. In a blog posts in September, Microsoft said:

we are committed to supporting C++/CLI for .NET Core to enable easy interop between C++ codebases and .NET technologies such as WPF and Windows Forms. This support isn’t going to be ready when .NET Core 3.0 first ships, but it will be available in .NET Core 3.1 which ships with Visual Studio 2019 16.4

Using Visual Studio 2019 16.4.x and targeting .NET Core 3.1, I have tried to create a demo WinForms app using C++/CLI. However, it does not work.

First of all, C++/CLI projects targeting .NET Core must be DLLs:

error NETSDK1116: C++/CLI projects targeting .NET Core must be dynamic libraries.

So I tried keeping the Win Forms code in a C++/CLI DLL compiled with /clr:netcore and running it from a native app. However, I get a runtime exception:

Unhandled exception. System.BadImageFormatException: Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. An attempt was made to load a program with an incorrect format. File name: 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (0x8007000B)

I have referenced in the C++/CLI project the System.Windows.Forms.dll from c:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App\3.1.0\, which is the location of the Microsoft.WindowsDesktop.App 3.1.0 runtime.

Is this supposed to work and I'm not doing something right?

like image 979
Marius Bancila Avatar asked Jan 13 '20 07:01

Marius Bancila


1 Answers

I had similar issue with my simple sample of .NET Core C# executable using the C++/CLI (managed C++) .Net Core DLL. Eventually figured out that I needed to explicitly set my C# executable target from Any CPU to x64. Most of the time it comes down to 32 bit / 64 bit mismatch.

like image 98
Slobodan Savkovic Avatar answered Sep 20 '22 08:09

Slobodan Savkovic