C++/CLI Support in .Net Core - c++-cli

Our project structure is like,
native.dll :- This contains pure native code written in c\c++.
This native.dll exposes some functions using *def file.
Wrapper Library(wrapper.dll compiled with .Net framework v4.0) :-
In order to use functionality of native.dll, a Wrapper lib(wrapper.dll)
is written in C++\CLI using :clr\oldsyntax. This wrapper has all
code of Interoperability and Marshalling.
Application(Console App v4.0) directly uses wrapper.dll to use functionality provided
by native.dll.
Now this project needs to run in .Net Core. This means we will have an
.Net Core application that will reference wrapper.dll that in turn will refer
native.dll.
I know this will not directly work. But the issue is whether .Net Core(CoreCLR) supports
C++\CLI (clr\oldsyntax) runtime environment ?
If no, what can be the possible solutions to this application work ?

whether .Net Core(CoreCLR) supports C++\CLI (clr\oldsyntax) runtime environment ?
As far as I know there is no plan to support C++/CLI with .NET Core.
If no, what can be the possible solutions to this application work ?
You can (should) provide a C API. Mono e. g. supports P/Invoke and .NET Core also supports P/Invoke (see also this Stack overflow question and this DllMap related ticket).
Update (2022-09-02): This answer is from 2016. See the other answers (e.g., this) for what is possible with recent .Net Core versions.

Officially announced eventually...
(next wish... support linux # .Net 5 ^^)
https://devblogs.microsoft.com/cppblog/the-future-of-cpp-cli-and-dotnet-core-3/
C++/CLI will have full IDE support for targeting .NET Core 3.1 and higher. This support will include projects, IntelliSense, and mixed-mode debugging (IJW) on Windows. We don’t currently have plans for C++/CLI for targeting macOS or Linux. Additionally, compiling with “/clr:pure” and “/clr:safe” won’t be supported for .NET Core.
The first public previews for C++/CLI are right around the corner. Visual Studio 2019 16.4 Preview 1 includes an updated compiler with “/clr:netcore”
Updat: From replied of origin url:
"We are still working on the IDE and MSBuild integration, so I can’t share a sample project quite yet. Once it’s available, likely with 16.4 Preview 2 or 3"
(16.4 Preview1 cannot create C++/CLI with .NetCore project.)
191015
16.4 Preview2 Released.
I'v tried asp.net core 3.1 with c++/CLI dll, it works.
(need set plateform to x64 both asp.net core and c++/CLI dll)

.net Core team will only commit (now?) to supporting C++/CLI for Windows only.
The intention was to deliver it for .net Core 3.0. While I haven't found explicit mention of it yet in the release notes, C++/CLI support was a prerequisite for delivering WPF (windows-only), which is now supported in .net Core 3.0.
Support mixed-mode assemblies on Windows - #18013
This issue (#18013) will track progress toward supporting loading and running
mixed-mode assemblies on CoreCLR. The main goal is to provide support
for WPF and other existing C++/CLI code on .NET Core. Some of the work
will be dependent on updates to the MSVC compiler.
The github issue (#659) mentioned above by #Tomas-Kubes, Will CoreCLR support C++/CLI crossplat? - #659, is about cross-platform C++/CLI.
BTW, I am getting compiler warnings on "clr\oldsyntax" with VS2017/.net-4.7. So this compiler flag is already deprecated.
UPDATE: This isn't coming till .Net Core 3.1

Another potential solution (though obviously quite a difficult task) if you want to stick with C++ (i.e. expose an OO interface to .NET) might be to have a look at CppSharp from the mono project. It is able to expose native C++ code through an automatically generated C# wrapper. It supports Windows, Linux as well as OSX. However, I don't know if the generated code can be compiled to a .NET standard target (didn't try to). I can only suppose it would because the generated code does not use any fancy API (it is basically interop and marshalling code); and, by the way, it is also possible to customize the generation process (although, once again, probably not an easy task).

For those who are looking at this for general .Net Core stuff without specific clr parameters (as this is a high result on google) Microsoft have written a guide on how to port C++/CLI to .Net Core:
https://learn.microsoft.com/en-us/dotnet/core/porting/cpp-cli
Port a C++/CLI project
To port a C++/CLI project to .NET Core, make the following changes to the .vcxproj file. These migration steps differ from the steps needed for other project types because C++/CLI projects don't use SDK-style project files.
Replace <CLRSupport>true</CLRSupport> properties with <CLRSupport>NetCore</CLRSupport>. This property is often in configuration-specific property groups, so you may need to replace it in multiple places.
Replace <TargetFrameworkVersion> properties with <TargetFramework>netcoreapp3.1</TargetFramework>.
Remove any .NET Framework references (like <Reference Include="System" />). .NET Core SDK assemblies are automatically referenced when using <CLRSupport>NetCore</CLRSupport>.
Update API usage in .cpp files, as necessary, to remove APIs unavailable to .NET Core. Because C++/CLI projects tend to be fairly thin interop layers, there are often not many changes needed. You can use the .NET Portability Analyzer to identify unsupported .NET APIs used by C++/CLI binaries just as with purely managed binaries.
Build without MSBuild
It's also possible to build C++/CLI projects without using MSBuild. Follow these steps to build a C++/CLI project for .NET Core directly with cl.exe and link.exe:
When compiling, pass -clr:netcore to cl.exe.
Reference necessary .NET Core reference assemblies.
When linking, provide the .NET Core app host directory as a LibPath (so that ijwhost.lib can be found).
Copy ijwhost.dll (from the .NET Core app host directory) to the project's output directory.
Make sure a runtimeconfig.json file exists for the first component of the application that will run managed code. If the application has a managed entry point, a runtime.config file will be created and copied automatically. If the application has a native entry point, though, you need to create a runtimeconfig.json file for the first C++/CLI library to use the .NET Core runtime.
There are some more nuances but these are the actual steps to port

Related

Can you import a package targeting full framework into an ASP.NET Core 3+ application?

My understanding is that, starting with ASP.NET Core 3.0, .NET Framework is an unsupported target framework, and thus you can only run on the .NET Core runtime.
If this is the case, what NuGet packages can be imported into an ASP.NET Core 3 app?
I assume that you could reference any package that targets netstandard, but what about packages that only target the full framework (i.e., a legacy package that only targets net45)?
What happens if the package you import references an assembly that's not part of .NET Core—i.e., System.Drawing?
TL;DR: You can still reference (packages which depend upon) .NET Framework assemblies from .NET Core 3 and even .NET 5, but you will receive a runtime error if you call into any code which relies upon APIs or libraries not (yet) supported by .NET Core. You can discover these using Microsoft's .NET Portability Analyzer
Background
First off, you're correct that ASP.NET Core 3.x applications can no longer target the .NET Framework, as announced by Microsoft in 2018. That capability previously allowed ASP.NET Core applications to call into .NET Framework libraries, and thus offered an intermediate solution for web applications migrating to .NET Core.
Note: Since the .NET Framework only runs on Windows machines, writing ASP.NET Core web applications which targeted the .NET Framework implicitly restricted those applications to running on Windows.
Behavior
Even when targeting .NET Core or now .NET 5, however, you're still able to reference .NET Framework packages and assemblies, assuming you're on a Windows machine and have the corresponding .NET Framework installed. The inner workings of this are a bit involved, but the short of it is that .NET Core and .NET 5 will evaluate .NET Framework assembles as though they are .NET Standard assemblies. If the API call is also implemented in the .NET Core runtime, it will work fine—but if the API call is exclusively part of .NET Framework, you'll receive an exception.
Surprise! It's really important to emphasize that this is a runtime exception. You will still be able to reference the .NET Framework assembly, write calls to problematic members, and compile your code without any warnings. But as soon as you call into code dependent on a .NET Framework-specific assembly, you'll receive the runtime exception.
Example
With .NET 3.0, a significant portions of .NET Framework libraries have been ported over to .NET Core. In fact, this includes most of the System.Drawing libraries you referenced as an example—though there are good reasons you may not want to use them. If you dig a bit deeper, however, there are plenty of libraries which remain unsupported. One obvious example is the WebConfigurationManager, which could be used to access configuration settings from web.config files.
.NET Framework Code
So, as an example, let's say you have the following function in a .NET Framework class library, which returns an array of keys from your web.config's <AppSetting>s element:
public static class Configuration
{
public static string[] GetAppSettings() => System.Web.Configuration.WebConfigurationManager.AppSettings.AllKeys;
}
ASP.NET Core Code
And then, in an ASP.NET Core controller, you expose an endpoint to retrieve this data:
public class MyController: Controller
{
public IActionResult ApplicationKeys() => Content(String.Join(", ", Configuration.GetAppSettings()));
}
Exception
In an ASP.NET Core 2.x application targeting the .NET Framework, this will work just fine. In an ASP.NET Core 3.x or ASP.NET Core 5 application, however, you'll receive the following runtime error when you call the /My/ApplicationKeys/ route:
System.TypeLoadException: 'Could not load type 'System.Web.Configuration.WebConfigurationManager' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.'
Avoiding Surprises
If you're anything like me, this will make you incredibly nervous. You'd much rather receive design-time errors—or, at least, compile-time warnings—as soon as you attempt to call into a library relying upon unsupported code. Fortunately, Microsoft offers a .NET Portability Analyzer, which is also available as a Visual Studio Extension, for exactly this purpose.
As of .NET 5, there's also a compatibility analyzer built into the SDK which will identify calls that are not supported by the .NET 5 runtime on particular platforms. This requires that target libraries explicitly annotate their types with the [SupportedOSPlatform()] attribute, so you won't get any warnings for legacy .NET Framework types. But this will help identify similar types of compatibility issues for libraries targeting a variety of platforms.
Example
If you run the Portability Analyzer on the above sample code, for example, it will output an Excel spreadsheet identifying that T:System.Web.Configuration.WebConfigurationManager is Not Supported in e.g. .NET Core,Version=v3.1 or .NET Standard + Platform Extensions,Version=v2.0.
Note: Microsoft used to offer an API Analyzer as a NuGet package, which promised to provide design-time analysis in Visual Studio. Unfortunately, the code hasn't been updated in two years, and the latest release is 0.2.12-alpha. In my evaluation, it was not effective at identifying issues.
Sample Project
I've put together a sample project on GitHub which demonstrates the above behavior. It includes the following projects:
ASP.NET Core 2.0 Website targeting .NET Framework 4.8
ASP.NET Core 3.1 Website targeting .NET Core 3.1
.NET Framework class library with calls to the legacy WebConfigurationManager
Both ASP.NET Core websites include two endpoints which call into the same .NET Framework 4.8 class library. The first is a "Hello world" example which will execute fine on both projects, since it relies exclusively on common APIs:
http://localhost:5000/Basic/Index
The second will fail on the ASP.NET Core 3.1 project, since it calls into the legacy WebConfigurationManager API:
http://localhost:5000/Basic/Configuration
Disclaimer: This is a quick and dirty repository that I put together to verify my understanding prior to posting this. If there's interest, I'll tidy it up and document it. For now, however, it may prove useful for those of you who need to see this in action.
Acknowledgments
#Chris Pratt offered an excellent answer covering similar material last year. It's worth reading.

Mixing ASP.NET Core with older .Net Framework code

I have some legacy .NET code that I would like to wrap with an API.
The code is a mixture of ASP.NET Webforms and .NET Framework 4.0
I'm hoping to use the new ASP.NET Core Web API and have created a new solution based on this framework and added the legacy code as existing projects.
Everything builds OK but when I try and call some of the legacy code I get the following error:
System.TypeInitializationException occurred HResult=0x80131534
Message=The type initializer for 'TreeManager' threw an exception.
Source=
Inner Exception 1: FileNotFoundException: Could not load file or
assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'. The system cannot find the file
specified.
This is the code I call:
TreeManager.LoadEvent += LoadTree;
public class TreeManager
{
...
public static event EventHandler<LoadEventArgs> LoadEvent;
...
}
I tried updating the legacy code to .NET 4.5.2 but get the same error.
I wrapped the legacy code with an API using ASP.NET MVC 4 API 2 and all worked well.
Is it possible to do this and, if so, what changes do I need to make?
First, you can choose to target either .NET Core or the full framework with a ASP.NET Core app. Just because it's "Core" doesn't mean you have to use .NET Core with it. If you're utilizing legacy APIs, you may be forced to run on the full framework.
If you need or simply want to use .NET Core, so that the app can be deployed outside of a Windows environment, then you'll need to migrate any APIs that aren't supported to alternative APIs or potentially rewrite functionality if no alternative API exists.
.NET Core 2.0 supports .NET Standard 2.0, which has a very large API footprint. Because of this, Microsoft opened up compatibility with legacy .NET Framework libraries and packages. However, no guarantees are made that you can fully utilize those libraries and packages. Just because you can add the dependency doesn't mean you can utilize all the APIs. That's likely what you're running into here. This particular set of APIs has a dependency on System.Web, which is not a part of .NET Core.
Recently, Microsoft has released some tools to make migration scenarios like this easier. First, there's the .NET API Analyzer, a NuGet package which will add Intellisense callouts to API calls that are not compatible with various targets. This will help you track down code that needs to be changed, and alert you when you're writing new code, that you need to do things in a different way than you might be used to.
Second, there's the Windows Compatibility Pack for .NET Core, another NuGet package that shims in support for a lot of older Windows-only APIs from the full framework. This can give you a bit of breathing room during your migration, reducing the amount if things you need to change, somewhat. Though, you are still encouraged to switch out this code eventually as well, eventually weaning your application off of the dependency altogether.
Finally, if none of this helps, you may simply have to find an alternative. That might require installing a third-party NuGet and rewriting some code to work with that instead of what you were using before.
No one ever claimed migrating was easy; it's always an uphill battle. If you don't have the bandwidth to do it now, simply target the full framework and call it a day. Otherwise, dig in and tackle it as best you can.

Assembly.GetExecutingAssembly() available in .NET Core?

Need to embed a json file as a source for testing in my .NET Core application. The author of this post http://codeopinion.com/asp-net-core-embedded-resource/ provided sample code that included the use of var assembly = Assembly.GetExecutingAssembly();However when I try this I get the error: Cannot resolve symbol ‘GetExecutingAssembly’ and ‘Assembly’ does not contain a definition for ‘GetExecuringAssembly’
If you are targeting .NET Standard 1.5 or above, you may call any of the following:
System.Reflection.Assembly.GetExecutingAssembly();
System.Reflection.Assembly.GetEntryAssembly();
System.Reflection.Assembly.GetCallingAssembly();
If targeting earlier versions of .NET Standard then the typeof(SomeClass).GetTypeInfo().Assembly method is the only way.
There is no "static" Assembly class in .NET Standard prior to version 1.5. Instead you have to do something like:
typeof(<AClassHere>).GetTypeInfo().Assembly
Where <AClassHere> should be replaced by the name of a class/type in the assembly you wish to load.
Nope, it's not available in .NET Core 1.0/1.1.
However, if I remember correctly it will be back in .NET Core 2.0 and the netstandard2.0 which is to be released later this year, which will have a much bigger API surface and increased compatibility with libraries written against .NET >= 4.5 making it easier to port these to .NETStandard 2.0/2.1.
But many of the APIs implementations will be platform dependent. Means, you will be able to call SomeAPI.GetSomething() everywhere, but if run on .NET Core it may throw a PlatformNotSupportedException.
But most APIs about assembly scanning and discovering should be back in .NET Core/Standard 2.0. Stuff around AppDomain will still be missing as there are no AppDomains in .NET Core and processes should be used for isolation.

changing the dll's target framework from .NET Framework to .NETCORE

I have the source code of a dll project that Targets .NET Framework. And I'm current developing a Universal App, I want to reference that dll to my project but it is not applicable since the Universal App uses a .NET CORE and that dll is specifically targets .NET Framework.
I'm thinking that I can change the dll's Target Framework since I have the source code but I don't know how.
Or is there another way of solving this?
I don't think there's an automated way to convert the library directly (if anyone knows a way, would be more than happy to hear about it).
However, sine you have the source code you can manually move the code.
Create a new Universal Application Class library and start move the code from the old library in there.
Chances are, not everything will work, since there are pretty major differences between namespaces and APIs between .NET framework and .NET core but at least you'll know what you need to change. I would recommend a modular approach where you include portions of the library, make sure it compiles and so on.

Unable to resolve assemblies that use Portable Class Libraries

I'm having a problem with assembly resolution on an end-user machine and I believe it's related to using Portable Class Libraries....
I have a .NET 4.0 application that was originally written in Visual Studio 2010. Recently we upgraded to Visual Studio 2012 and we've created a few projects that are Portable Class Libraries. I don't believe we need these features now, but we're also building a Windows 8 Store application that might benefit from these libraries.
When I compile my project, what exactly does the portable library feature do? I expect that it allows me to run it on different frameworks without modification or recompiling.
When I look at the library in reflector dotPeek it shows the Platform attribute as:
.NETPortable,Version=v4.0,Profile=Profile5
And the references seem 2.0-ish:
mscorlib, Version=2.0.5.0
System, Version=2.0.5.0
System.Runtime.Serialization, Version=2.0.5.0
When I run the application on this end-user's machine, I see an error in the log file:
Could not load file or assembly, 'System.Core, Version=2.0.5.0...'
Googling System.Core 2.0.5.0 seems to refer to SilverLight -- which appears to be one of the targeted frameworks.
This machine does not have Visual Studio installed, but has .NET 4.0 (4.0.3 update)
Is there something I should be doing differently to compile, something I should investigate in my dependencies or something I should be looking to install on the end-user machine? What does the 2.0.5.0 refer to?
For .NET 4, you need an update (KB2468871) for Portable Class Libraries to work. From the KB Article:
Feature 5
Changes to the support portable libraries. These changes include API
updates and binder modifications. This update enables the CLR to bind
successfully to portable libraries so that a single DLL can run on the
.NET Framework 4, on Silverlight, on Xbox, or on the Windows Phone.
This update adds public Silverlight APIs to the .NET Framework 4 in
the same location. The API signatures will remain consistent across
the platform. All modifications are 100 percent compatible and will
not break any existing code.
Also see the "Deploying A .NET Framework App" section of the MSDN Portable Class Library Documentation.
EDIT: Actually, if the machine has .NET 4.0.3 installed as you mention, that should be sufficient. Can you double-check to make sure that it is actually installed?