Accessing WinRT from Desktop Apps (Part 2)

September 24, 2012

no comments

In the previous post we’ve seen how to instantiate WinRT objects using the raw (Ro, pun intended) API. In this post, we’ll see some shortcuts to make our lives a little easier.

These shortcuts are part of the Windows Runtime template Library (WRL). This is a helper library, similar in spirit to the Active Template Library (ATL) used for classic COM work.

First we need to include the main WRL header, <wrl.h>. Also, we’ll include another header with some extra helpers, that are not included with the primary header:

#include <wrl.h>
#include <wrl/wrappers/corewrappers.h>

Next, we’ll add using namespace statements to make our lives a little easier:

using namespace Windows::Foundation;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

Now for the real work in main().

To initialize WinRT on the current thread, we called RoInitialize() and at the end its counterpart, RoUninitialize(). A simple RAII class wraps these calls in the constructor/destructor, named RoInitializeWrapper:

RoInitializeWrapper init(RO_INIT_MULTITHREADED);

Next, we need an HSTRING that represents the Calendar’s full class name. Instead of calling WindowsCreateString etc., we can use the HString class wrapper provided by WRL:

HSTRING hClassName = HString::MakeReference(RuntimeClass_Windows_Globalization_Calendar).Get();

HString::MakeReference calls WindowsCreateStringReference, which is a way to create an “unmanaged” HSTRING, that does not need to be deleted because it points to memory that is already allocated in some other means; in this case, it’s a C-style string already defined in <windows.globalization.h> with the Calendar’s full class name.

To create the actual instance we’ll use another helper function, Windows::Foundation::ActivateInstance that accepts a class name (HSTRING) and returns an interface pointer to any supported interface. There’s no need to request IInspectable and then do a QueryInterface – the function takes care of that:

ComPtr<ICalendar> spCalendar;
HRESULT hr = ActivateInstance(hClassName, &spCalendar);

ComPtr<T> is WRL’s smart pointer (similar to CComPtr<T> from ATL).

That’s it. We can now use the Calendar in any way we want.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>