6
votes

.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?

2
I am encountering related problems with my own C++/CLI dll and targeting .NET Core 3.1, I found a number of problems. Filed a bug report for one of them. I was able to leave the C++/CLI targeting .NET Framework 4.8 and only have my client C# app target .NET Core 3.1, but then I started getting the exceptions like what you are getting, and even weirder only in DEBUG builds. I suspect MS has some work to do.Joe

2 Answers

0
votes

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.

-1
votes

I found this document on the microsoft's website. It explains how to do it, and is accompanied by a github repo you can easily clone and try out yourself: https://devblogs.microsoft.com/cppblog/porting-a-c-cli-project-to-net-core/