August 6th, 2021

Using Windows Runtime interop methods from C++/WinRT: Some helper functions

Last time, we saw how to combine various pieces of C++/WinRT in order to call a Windows Runtime interop interface and capture the result as a C++/WinRT object.

There is some redundancy in the pattern, since you have to name the interface twice: Once to obtain it from the factory, and again to name the member function.

A little helper function will save some typing:

template<
    typename Result,
    typename WinRTType,
    typename InteropInterface,
    typename... InteropArgs,
    typename... Args>
auto capture_interop(
    HRESULT (STDMETHODCALLTYPE InteropInterface::*method)(InteropArgs...),
    Args&&... args)
{
    return winrt::capture<Result>(
        winrt::get_activation_factory<WinRTType, InteropInterface>(),
        method, std::forward<Args>(args)...);
}

Our example last time then simplifies to

capture_interop<
    winrt::IAsyncOperation<winrt::WebTokenRequestResult>,
    winrt::WebAuthenticationCoreManager>(
    &::IWebAuthenticationCoreManagerInterop::RequestTokenForWindowAsync,
    window,
    static_cast<::IInspectable*>(winrt::get_abi(request)));

There is a corresponding pattern for interop interfaces on instance objects.

template<
    typename Result,
    typename InteropInterface,
    typename... InteropArgs,
    typename... Args>
auto capture_interop(
    winrt::IUnknown const& o,
    HRESULT (STDMETHODCALLTYPE InteropInterface::*method)(InteropArgs...),
    Args&&... args)
{
    return winrt::capture<Result>(
        o.as<InteropInterface>(), method, std::forward<Args>(args)...);
}

Usage for this would be something like

winrt::UserActivity activity = ...;

auto session = capture_interop<winrt::UserActivitySession>(
    activity, &::IUserActivityInterop::CreateSessionForWindow, window);

These helper functions are part of the Windows Implementation Library, documented here: capture_interop.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.