Search code examples
c++.netvisual-studiowindows-runtimec++-winrt

How to include System in C++/WinRT console application


Using Visual Studio 2019 16.10.2 how do you include .NET components in a C++ / WinRT Console programme?

The indexOf method of IVector requires a UInt32 struct from System.

How is the System utilised in this context? Trying to use the namespace results in a

"System' : a namespace with this name does not exist"

This has been covered already on SO, but only for a C++/CLI application and not in the context of a C++/WinRT console app. The solutions provided in that post also do not work.

#include "pch.h"

#include <Windows.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>

using winrt::Windows::Foundation::Collections::IVector;
using namespace System;

int main()
{
    IVector<int> foo;
    foo.Append(1);
    UInt32 bar;
    foo.indexOf(1, bar);

    return EXIT_SUCCESS;
}

In this case pch.h is empty.


Solution

  • When you select the appropriate language from the documentation's language dropdown list in the top right corner (C++/WinRT) you'll see the C++/WinRT-specific signature:

    bool IndexOf(T const& value, uint32_t & index);
    

    You'll need to replace

    UInt32 bar;
    

    with

    uint32_t bar{};