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.
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:
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);
That’s it. We can now use the Calendar in any way we want.