Skip to content

Automatically import NuGet packages from intermediate C# projects into C++/CLI projects. #4

@crud89

Description

@crud89

Adding NuGet packages to C++/CLI projects is surprisingly hard. Whilst purely managed assemblies can simply be referenced by a C++/CLI project, the TargetFramework property not beeing properly set for C++/CLI projects, results in errors when NuGet tries to restore the package:

You are trying to install this package into a project that targets 'native,Version=v0.0', but the package does not contain any assembly references or content files that are compatible with that framework.

You might also experience other errors, such as NU1201 or NU1202.

Whilst in theory it is possible for C++/CLI projects to use NuGet packages that target the same .NET Framework version, it is currently not properly implemented by Microsoft. The naïve approach of defining a VS_PACKAGE_REFERENCE, as you would do for a C# project, will result in NuGet not beeing able to resolve the target framework for the project and you will receive the errors mentioned earlier. There are two possible workarounds for this issue, both of which require an intermediate C# project that has a VS_PACKAGE_REFERENCE set, so that MSBuild is able to restore the package. In this template this could be the CommonLib project.

  1. Write a wrapper class for all the interfaces you wish to call. Obviously not very feasible.
  2. Use a hard reference (i.e. VS_DOTNET_REFERENCE_*) to the package assembly. However, this approach is not ideal, since you have to know where the current NuGet package cache resides, which might cause forward compatibility problems.

The second option could be made much more feasible by exploiting the fact, that the proper assemblies are automatically copied over to the output directory during the build. If those assemblies could be added to the CMake export config for the project, than a simple TARGET_LINK_LIBRARIES would be enough to properly reference them within the C++/CLI project or other dependent projects.

However, my CMake expertise is actually limited and I spent way to many hours trying to fix this issue. So if you feel you could contribute to a solution to this problem, feel free to join the discussion in this issue or open an PR! 🙂

Related resources:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions