An Update on C++/CLI and .NET Core
The first public release of our C++/CLI support for .NET Core 3.1 is now available for public preview! It is included in Visual Studio 2019 update 16.4 Preview 2. We would love it if you could try it out and send us any feedback you have. For more info about what this is and the roadmap going forward, check out my last post on the future of C++/CLI and .NET Core.
To get started make sure you have all the necessary components installed. C++/CLI support for desktop development is an optional component, so you will need to select it on the installer’s right pane:
You will also need the .NET Core cross-platform development workload. It installs everything you need including the .NET Core 3.1 SDK:
Creating a C++/CLI .NET Core Project
First, you will want to create a “CLR Class Library (.NET Core)” or “CLR Empty Project (.NET Code)”. The Class library template includes some additional boiler plate to set up an example class and precompiled header that may make it easier to get started. The empty project is ideal for bringing in existing C++/CLI code. Retargeting existing C++/CLI projects to .NET Core isn’t recommended.
There isn’t currently a template for C++/CLI console or Windows applications that can be used with .NET Core. Instead you must put application entry point outside of the C++/CLI code. In general, we strongly recommend keeping the C++/CLI projects as narrow in scope as possible to handle just the interoperability between .NET Core and other C++ code.
Once you create one of these projects, you can reference it from other .NET Core projects like any other class library – with one important caveat. .NET Core projects are typically architecture agnostic. You see this as the architecture “Any CPU” in the Configuration Manager and “MSIL” in the build logs. This is the default for all .NET Core projects. If you reference any C++/CLI class libraries, you must specify an explicit architecture for the non-C++ projects instead of “Any CPU”.
You can set a project’s architecture by using the Configuration Manager.
If the architectures don’t match, you will see this warning and attempting to load the C++/CLI class library will fail at runtime:
To resolve this, make sure all projects in the solution are using the same architecture of “x86” and “Win32” or “x64”. If you are using ASP.NET Core, there is an additional consideration. Your projects also need to match the architecture of IIS Express. This is typically “x64”. If you see a “500 server error” due to the loader failing, this may be what the problem is.
Send us Feedback
Please try this out. We’d love to hear your feedback to help us prioritize and build the right features. We can be reached via the comments below or email (firstname.lastname@example.org). You also can always send us general feedback via Developer Community.