.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=184.108.40.206, Culture=neutral, PublicKeyToken=b77a5c561934e089'. An attempt was made to load a program with an incorrect format. File name: 'System.Windows.Forms, Version=220.127.116.11, 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?
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.
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/
User contributions licensed under CC BY-SA 3.0