Search code examples
c#c++uwpwin-universal-appc++-cx

How to reference C# UWP Class Library from C++ UWP App


I am getting a COMException when trying to reference a method in a C# UWP class library from a C++ UWP app. This is happening with the most basic of setups, so I must be doing something wrong.

Repro:

  1. Using Visual Studio (I'm using 16.5.4), Create a new "Blank App (Universal Windows - c++/CX)"
  2. Add to the solution a new "Windows Runtime Component (Universal Windows)", C#, Called "ClassLib"
  3. Add this method to Class1.cs: public static int GetNumber() { return 22; }
  4. Modify the MainPage constructor to look like this:
using namespace ClassLib;
MainPage::MainPage()
{
    InitializeComponent();

    auto foo = Class1::GetNumber();
}
  1. Execute the application. This exception happens in the MainPage constructor:
Exception thrown at 0x76984402 in UWPApp.exe: 
  Microsoft C++ exception: 
    Platform::COMException ^ at memory location 0x0421DD44. 
    HRESULT:0x80131040 The text associated with this error code could not be found.

Solution

  • This issue is due to calling .net based WinRT components from C++/CX or C++ WinRT projects. To make it work, you can add Microsoft.Net.Native.Compiler nuget package in your c++/cx project and install it first. Then Right-click the project -> Unload Project -> Edit .vcxproj. After that, adding the following properties in it.

    <PropertyGroup>
        <UseDotNetNativeToolchain Condition="'$(Configuration)'=='Release'">true</UseDotNetNativeToolchain>
        <DotNetNativeVersion>2.2.3</DotNetNativeVersion>
    </PropertyGroup>
    

    Note that, replace the 2.2.3 version above with the version of Microsoft.Net.Native.Compiler nuget package you installed. For more details about it, you can refer to this similar thread.