问题
.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?
来源:https://stackoverflow.com/questions/59711996/c-cli-targetting-net-core-3-1