Christophe Pichaud on Microsoft Technologies - MVP Developer Technologies 2019-2020
Using WRL (Windows Runtime Library) with Standard ISO C++WRL is a C++ template library shipped with the Windows SDK 8 and 8.1. It allows to build WinRT components.
WinRT components are used in Windows Store Apps.
Microsoft provides a new C++ set of compiler extensions for building WinRT components but this is not the standard ISO C++ and has some changes with operator ^ and ref keywords.
Thoses extensions are aligned with the Managed C++ syntax but it generates native code.
But a lot of developers want to develop using the real and standard ISO C++ so this article is dedicated only with standard ISO C++.
It is possible to write WinRT components using the WRL library and consume them into JS, C# or C++ XAML apps.
To start using WRL, you can download the WRL project template.
First, a WinRT component is based on COM. So you have to provide a MIDL file with various interfaces.
In COM, you used to inherit from IUnknown interface but with WinRT, you have inherit from IInspectable.
import "inspectable.idl"; import "Windows.Foundation.idl"; #define COMPONENT_VERSION 1.0 namespace Library1 { interface ILogger; runtimeclass Logger; [uuid(3EC4B4D6-14A6-4D0D-BB96-31DA25224A15), version(COMPONENT_VERSION)] interface ILogger : IInspectable { HRESULT LogInfo([in] HSTRING value); } [version(COMPONENT_VERSION), activatable(COMPONENT_VERSION)] runtimeclass Logger { [default] interface ILogger; } }
Now we have a MIDL file, we can provide a class to implement our methods.
Microsoft has chosen to put every component in the ABI namespace so we respect this convention.
#pragma once #include "Library1_h.h" namespace ABI { namespace Library1 { class Logger : public RuntimeClass<ILogger> { InspectableClass(L"Library1.Logger", BaseTrust) public: STDMETHOD(LogInfo)(HSTRING value); }; ActivatableClass(Logger); } }
You can see that there are few lines of code. If you used to write COM compoenents using ATL, you can see the differences.
You can see that special type HSTRING wich is the new string type available for all languages. It is not BSTR anymore.
WRL does not know about IDispatch and OLE types. You have to provide only Windows type in IDL file.
A WinRT class have to include the InspectableClass macro wich provides the name of the component. It is like the ProgId in COM.
You can notice there is also the ActivatableClass macro.
Let's look at the CPP implementation file.
#include "pch.h" #include "Logger.h" namespace ABI { namespace Library1 { STDMETHODIMP Logger::LogInfo(HSTRING value) { HString str; str.Set(value); std::wstring ws = str.GetRawBuffer(nullptr); return S_OK; } } }
To handle HSTRING type, you can use the HString class. It allows to return std::wstring.