How do I call a C++ WinRT component in .NET 6?

yoyodyne01 46 Reputation points
2023-01-20T20:30:07.9033333+00:00

I have a WinUI3 app targeting .NET 6 and need to call some legacy C++ code which is compiled in a separate component for which I have the source. I followed this example:
https://learn.microsoft.com/en-us/windows/apps/develop/platform/csharp-winrt/net-projection-from-cppwinrt-component
however I'm not packaging my component+projection as a nuget package. Instead it's one solution, which contains the WinUI3 C# app, the C# projection, and the C++ component. The only problem now is that the C++ component isn't getting deployed to the appx package so the app throws a class not registered exception at runtime. My dependencies are App->Projection->Component but component.dll isn't copied to the appx folder.

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
752 questions
{count} votes

1 answer

Sort by: Most helpful
  1. SanthiSwaroopNaikBukke-4908 595 Reputation points
    2023-01-20T20:35:18.1633333+00:00

    To call a C++ WinRT component in .NET 6, you will need to use the Windows Runtime C++ Template Library (WRL) to create a C++/WinRT projection of the component. This projection can then be consumed in C# or other .NET languages using the Windows.Foundation.WinRT namespace.

    Here is an example of how you can consume a C++ WinRT component in C# using WRL:

    1. In your C++ component, define the component's interface using the winrt::implements keyword.
    2. In your C# project, add a reference to the C++ component's projection. This can be done by adding a reference to the component's .winmd file, or by adding a reference to the component's project if it is part of the same solution.
    3. In your C# code, create an instance of the component's class using the new keyword and the component's class name.
    4. Call the component's methods and properties as you would with any other C# object.

    It's important to note that C++/WinRT is a standard C++ library, you need to make sure that your C++ code is compatible with C++/WinRT before you can call it from C#.