Building WinRT component with WRL(non C++/CX) and cppwinrt

The cppwinrt project focused to consume Microsoft provided OS winrt components and it doesn’t support building a winrt component(yet) although they mentioned it will be supported later.

Even though it’s not technically supported yet, we still can create a winrt component with WRL(pure C++ and non C++/CX) and still can get some benefits from using cppwinrt within WRL component.

For example, I created a WinRT sample component with WRL and exports IAsyncAction async methods from it. Inside the method, I utilized the cppwinrt provided coroutine method which easily can produce IAsync operations. See the following:

https://github.com/heejune/wrl-cppwinrt-sample/blob/async-support/SampleLib.Shared/DemoCore.cpp

There’s a DemoCore::GetCppwinrtDataasync method defined as this:

winrt::Windows::Foundation::IAsyncOperation<int> GetAsyncOp()
{
using namespace winrt;
using namespace Windows::Foundation;
for (int i = 0; i != 5; ++i)
{
co_await 5000ms;
}
co_return 1;
}
STDMETHODIMP DemoCore::GetCppwinrtDataAsync(::ABI::Windows::Foundation::IAsyncOperation<int>** value)
{
auto asyncOp = GetAsyncOp();
*value = reinterpret_cast<::ABI::Windows::Foundation::IAsyncOperation<int>*>(winrt::detach(asyncOp));
return S_OK;
}

view raw
democore.cpp
hosted with ❤ by GitHub

It just (detached and) returns the object which also returned from GetAsyncOp private method. GetAsyncOp is a coroutine function which also creates an instance of winrt::Windows::Foundation::IAsyncOperation. And that’s the winrt implementation of IAsyncOperation.

You can download the source project and test it from https://github.com/heejune/wrl-cppwinrt-sample/tree/async-support

Thanks,

Heejune

2 thoughts on “Building WinRT component with WRL(non C++/CX) and cppwinrt

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s