Skip to content

Instantly share code, notes, and snippets.

@kennykerr
Created April 18, 2017 15:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kennykerr/105f96d61f51b5773670844edec99d85 to your computer and use it in GitHub Desktop.
Save kennykerr/105f96d61f51b5773670844edec99d85 to your computer and use it in GitHub Desktop.
How to cast between C++/WinRT and C++/CX
template <typename T>
T^ to_cx(winrt::Windows::Foundation::IUnknown const& from)
{
return safe_cast<T^>(reinterpret_cast<Platform::Object^>(winrt::get_abi(from)));
}
template <typename T>
T from_cx(Platform::Object^ from)
{
T to{ nullptr };
winrt::check_hresult(reinterpret_cast<::IUnknown*>(from)->QueryInterface(winrt::put_abi(to)));
return to;
}
namespace cx
{
using namespace Windows::Foundation;
}
namespace winrt
{
using namespace Windows::Foundation;
}
void sample()
{
winrt::Uri uri(L"http://moderncpp.com/");
cx::Uri^ uri2 = to_cx<cx::Uri>(uri);
winrt::Uri uri3 = from_cx<winrt::Uri>(uri2);
assert(uri == uri3); // identity
assert(uri2->Domain == L"moderncpp.com");
assert(uri3.Domain() == L"moderncpp.com");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment