{"id":2143,"date":"2012-10-05T09:45:00","date_gmt":"2012-10-05T09:45:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/vcblog\/2012\/10\/05\/ccx-part-3-of-n-under-construction\/"},"modified":"2019-02-18T18:41:31","modified_gmt":"2019-02-18T18:41:31","slug":"ccx-part-3-of-n-under-construction","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cppblog\/ccx-part-3-of-n-under-construction\/","title":{"rendered":"C++\/CX Part 3 of [n]: Under Construction"},"content":{"rendered":"<p><em>See <a href=\"https:\/\/blogs.msdn.microsoft.com\/vcblog\/2012\/08\/29\/ccx-part-0-of-n-an-introduction\/\">C++\/CX Part 0 of [n]: An Introduction<\/a> for an introduction to this series and a table of contents with links to each article in the series.<\/em><\/p>\n<p>In this article, we&#8217;ll take a look at the how runtime classes are constructed. We&#8217;ll use the following <code>Widget<\/code> runtime class throughout this article:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">class<\/span>&nbsp;<span style=\"color: #2b91af\">Widget<\/span>&nbsp;<span style=\"color: blue\">sealed<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Widget()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;_number(0)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Widget(<span style=\"color: blue\">int<\/span>&nbsp;<span style=\"color: gray\">number<\/span>)&nbsp;:&nbsp;_number(<span style=\"color: gray\">number<\/span>)&nbsp;{&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;GetNumber()&nbsp;{&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;_number;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">private<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;_number;\n&nbsp;&nbsp;&nbsp;&nbsp;};<\/pre>\n<p>This type has both a default constructor and a constructor with an <code>int<\/code> parameter. C++\/CX runtime class constructors are largely the same as constructors for ordinary C++ class types. Like ordinary member functions, any constructor that is part of the public interface of the runtime class can only use Windows Runtime types in its signature. This rule applies to public and protected constructors of public runtime classes, because these form the interface of the runtime class. Otherwise, there isn&#8217;t much more to say about runtime class constructors.<\/p>\n<p>C++\/CX adds a new operator, <code>ref new<\/code>, that is used to construct an instance of a runtime class. For example, we can easily construct a <code>Widget<\/code> instance using either of its constructors:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">   <span style=\"color: #2b91af\"><span style=\"color: #000000\"> <\/span>Widget<\/span>^&nbsp;widgetZero  &nbsp;=&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">new<\/span>&nbsp;<span style=\"color: #2b91af\">Widget<\/span>();\n    <span style=\"color: #2b91af\">Widget<\/span>^&nbsp;widgetAnswer&nbsp;=&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">new<\/span>&nbsp;<span style=\"color: #2b91af\">Widget<\/span>(42);&nbsp;<\/pre>\n<p>The behavior of <code>ref new<\/code> is comparable to that of <code>new<\/code>: it takes the runtime class to be constructed and a set of arguments to be passed to the constructor of that runtime class, and it constructs an instance of that type. Whereas <code>new T()<\/code> yields a <code>T*<\/code> pointing to the new object, <code>ref new T()<\/code> yields a <code>T^<\/code>. In this respect, <code>ref new<\/code> is similar to the <code>make_shared<\/code> helper function that can be used to safely construct a <code>shared_ptr<\/code>.<\/p>\n<p>Much as we saw in the previous articles, aside from the syntactic tags that tell the compiler that <code>Widget<\/code> is a Windows Runtime type (e.g., <code>^<\/code> and <code>ref<\/code>), this code looks almost exactly like equivalent C++ code that works with ordinary C++ types. Constructors are declared the same way, and <code>ref new<\/code> is largely used in the same way as <code>new<\/code> is used. However, this syntactic simplicity hides quite a bit of complex machinery, which is what we&#8217;re going to investigate here.<\/p>\n<p>Because C++\/CX hides all of the complexity here, we&#8217;ll instead use WRL to explain how object construction works. So that we have somewhere to start, we&#8217;ll translate our <code>Widget<\/code> type into WRL. First the IDL that declares the <code>Widget<\/code> runtime type and its default interface, <code>IWidget<\/code>:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: #0000ff\">exclusiveto<\/span>(Widget)]\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">uuid<\/span>(ada06666-5abd-4691-8a44-56703e020d64)]\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">version<\/span>(1.0)]\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">interface<\/span>&nbsp;IWidget&nbsp;:&nbsp;IInspectable\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HRESULT&nbsp;GetNumber([<span style=\"color: blue\">out<\/span>]&nbsp;[<span style=\"color: blue\">retval<\/span>]&nbsp;<span style=\"color: blue\">int<\/span>*&nbsp;number);\n&nbsp;&nbsp;&nbsp;&nbsp;}\n &nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">version<\/span>(1.0)]\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #0000ff\">runtimeclass&nbsp;<\/span>Widget\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">default<\/span>]&nbsp;<span style=\"color: blue\">interface<\/span>&nbsp;IWidget;\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>And the C++ definition of the <code>Widget<\/code> type:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">    <span style=\"color: blue\">class<\/span>&nbsp;<span style=\"color: #2b91af\">Widget<\/span>&nbsp;:&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: #2b91af\">RuntimeClass<\/span>&lt;<span style=\"color: #2b91af\">IWidget<\/span>&gt;\n    {\n        <span style=\"color: #6f008a\">InspectableClass<\/span>(RuntimeClass_WRLWidgetComponent_Widget,&nbsp;<span style=\"color: darkslategray\">BaseTrust<\/span>)\n&nbsp;&nbsp;\n    <span style=\"color: blue\">public<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;\n        Widget()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;_number(0)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;}\n        Widget(<span style=\"color: blue\">int<\/span>&nbsp;<span style=\"color: gray\">number<\/span>)&nbsp;:&nbsp;_number(<span style=\"color: gray\">number<\/span>)&nbsp;{&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n        <span style=\"color: #6f008a\">STDMETHODIMP<\/span>&nbsp;GetNumber(<span style=\"color: blue\">int<\/span>*&nbsp;<span style=\"color: gray\">number<\/span>)&nbsp;{&nbsp;*<span style=\"color: gray\">number<\/span>&nbsp;=&nbsp;_number;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;<span style=\"color: #6f008a\">S_OK<\/span>;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n    <span style=\"color: blue\">private<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;\n        <span style=\"color: #2b91af\">INT32<\/span>&nbsp;_number;\n    };<\/pre>\n<p><em>Please note: for brevity, error handling code has been omitted from most of the examples in this article. When writing real code, please be sure to handle error conditions, including null pointers and failed HRESULTs.<\/em><\/p>\n<p>While this C++ <code>Widget<\/code> class defines two constructors, these constructors are <em>implementation details<\/em> of the <code>Widget<\/code> type. Recall from <a href=\"http:\/\/blogs.msdn.com\/b\/vcblog\/archive\/2012\/09\/05\/cxxcxpart01asimpleclass.aspx\">Part 1<\/a> that we only ever interact with a runtime class object via an interface pointer: since the constructors are not declared by any interface, they are not part of the public interface of the runtime class.<\/p>\n<h2>Where Do Widgets Come From?<\/h2>\n<p>The structure of a runtime class is an implementation detail of the particular language and framework that are used to implement the runtime class; thus, the way in which an object of such a type is constructed is also an implementation detail, since construction is inexorably linked to the structure of the type. Windows Runtime components are consumable from any language that supports the Windows Runtime, so we need a language-neutral mechanism for constructing runtime class objects.<\/p>\n<p>The Windows Runtime uses <em>activation factories<\/em> for constructing runtime class objects. An activation factory is a runtime class whose purpose is to construct objects of a particular runtime class type. We will define a <code>WidgetFactory<\/code> activation factory that constructs <code>Widget<\/code> objects.<\/p>\n<p>Like any other runtime class, an activation factory implements a set of interfaces. Every activation factory must implement the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br205779.aspx\"><code>IActivationFactory<\/code><\/a> interface, which declares a single member function: <code>ActivateInstance<\/code>. The <code>ActivateInstance<\/code> interface function takes no arguments and returns a default-constructed object. An activation factory can also implement user-defined factory interfaces that define other &#8220;construction&#8221; functions. For our <code>WidgetFactory<\/code>, we&#8217;ll use the following factory interface:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: #0000ff\">exclusiveto<\/span>(Widget)]\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">uuid<\/span>(5b197688-2f57-4d01-92cd-a888f10dcd90)]\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: blue\">version<\/span>(1.0)]\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">interface<\/span>&nbsp;IWidgetFactory&nbsp;:&nbsp;IInspectable\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HRESULT&nbsp;CreateInstance([<span style=\"color: blue\">in<\/span>]&nbsp;<span style=\"color: blue\">int<\/span>&nbsp;value,&nbsp;[<span style=\"color: blue\">out<\/span>]&nbsp;[<span style=\"color: blue\">retval<\/span>]&nbsp;Widget**&nbsp;widget);\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>A factory interface may only declare factory functions: each function must take one or more arguments and must return an instance of the runtime class. The <code>Widget<\/code> runtime class has only one non-default constructor, so we only need to declare a single factory function here, but it&#8217;s possible to define as many factory functions as are needed. When using C++\/CX, the compiler automatically generates a factory interface for each public <code>ref class<\/code>, with factory functions whose arguments correspond to those of each of the constructors of the <code>ref class<\/code>.<\/p>\n<p>In addition to defining a factory interface for the <code>Widget<\/code> type, we also need to annotate it in the IDL as being <em>activatable<\/em>. We do so using the <code>activatable<\/code> attribute, which has two forms, both of which we will use for our <code>Widget<\/code> type:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: #0000ff\">activatable<\/span>(1.0)]\n&nbsp;&nbsp;&nbsp;&nbsp;[<span style=\"color: #0000ff\">activatable<\/span>(IWidgetFactory,&nbsp;1.0)]<\/pre>\n<p>The first form declares the type as being default constructible. The second form declares that the <code>IWidgetFactory<\/code> is a factory interface for the runtime class. (The <em>1.0<\/em> in each is a version number; it is not relevant for this discussion.) When the midlrt compiler compiles the IDL file into a Windows Metadata (WinMD) file, it will use these attributes to add the correct set of constructors to the metadata for the runtime class.<\/p>\n<p>Next, we need to implement a <code>WidgetFactory<\/code> type that implements both the <code>IActivationFactory<\/code> and the <code>IWidgetFactory<\/code> interfaces. Instead of using the WRL <code>RuntimeClass<\/code> base class template, we&#8217;ll use the <code>ActivationFactory<\/code> base class template, which is designed to support activation factories.<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">class<\/span>&nbsp;<span style=\"color: #2b91af\">WidgetFactory<\/span>&nbsp;:&nbsp;<span style=\"color: blue\">public<\/span>&nbsp;<span style=\"color: #2b91af\">ActivationFactory<\/span>&lt;<span style=\"color: #2b91af\">IWidgetFactory<\/span>&gt;\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #6f008a\">InspectableClassStatic<\/span>(RuntimeClass_WRLWidgetComponent_Widget,&nbsp;<span style=\"color: darkslategray\">BaseTrust<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">public<\/span>:\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #6f008a\">STDMETHODIMP<\/span>&nbsp;ActivateInstance(<span style=\"color: #2b91af\">IInspectable<\/span>**&nbsp;<span style=\"color: gray\">widget<\/span>)&nbsp;<span style=\"color: blue\">override<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*<span style=\"color: gray\">widget<\/span>&nbsp;=&nbsp;Make&lt;<span style=\"color: #2b91af\">Widget<\/span>&gt;().Detach();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;*<span style=\"color: gray\">widget<\/span>&nbsp;!=&nbsp;<span style=\"color: blue\">nullptr<\/span>&nbsp;?&nbsp;<span style=\"color: #6f008a\">S_OK<\/span>&nbsp;:&nbsp;<span style=\"color: #6f008a\">E_OUTOFMEMORY<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #6f008a\">STDMETHODIMP<\/span>&nbsp;CreateInstance(<span style=\"color: blue\">int<\/span>&nbsp;<span style=\"color: gray\">value<\/span>,&nbsp;<span style=\"color: #2b91af\">IWidget<\/span>**&nbsp;<span style=\"color: gray\">widget<\/span>)&nbsp;<span style=\"color: blue\">override<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*<span style=\"color: gray\">widget<\/span>&nbsp;=&nbsp;Make&lt;<span style=\"color: #2b91af\">Widget<\/span>&gt;(<span style=\"color: gray\">value<\/span>).Detach();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;*<span style=\"color: gray\">widget<\/span>&nbsp;!=&nbsp;<span style=\"color: blue\">nullptr<\/span>&nbsp;?&nbsp;<span style=\"color: #6f008a\">S_OK<\/span>&nbsp;:&nbsp;<span style=\"color: #6f008a\">E_OUTOFMEMORY<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;};<\/pre>\n<p><code>ActivationFactory<\/code> provides a default implementation of the <code>IActivationFactory<\/code> interface; this default implementation simply defines <code>ActivateInstance<\/code> as returning <code>E_NOTIMPL<\/code>. This is suitable for runtime classes that are not default constructible; for runtime classes that are default constructible (like <code>Widget<\/code>), we need to override <code>ActivateInstance<\/code> to actually default construct an object.<\/p>\n<p><code>Make&lt;Widget&gt;()<\/code> is effectively equivalent to <code>new (nothrow) Widget()<\/code>: it dynamically allocates memory for a <code>Widget<\/code> and passes the provided arguments to the <code>Widget<\/code> constructor. Like <code>new (nothrow)<\/code>, it yields <code>nullptr<\/code> if allocation fails (remember, we can&#8217;t throw an exception from a function implementing an interface, we must return an HRESULT). It returns a <code>ComPtr&lt;Widget&gt;<\/code>; since we are returning the interface pointer, we simply detach the pointer and return it (the caller is responsible for calling <code>Release<\/code> on all returned interface pointers).<\/p>\n<p>That&#8217;s all we need to implement the <code>WidgetFactory<\/code> activation factory. If we can get an instance of the factory, we can easily create <code>Widget<\/code> objects. For example,<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">void<\/span>&nbsp;Test(<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">IWidgetFactory<\/span>&gt;&nbsp;<span style=\"color: blue\">const<\/span>&amp;&nbsp;<span style=\"color: gray\">factory<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n    &nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">IWidget<\/span>&gt;&nbsp;widget;\n    &nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">factory<\/span>-&gt;CreateInstance(42,&nbsp;widget.GetAddressOf());\n    &nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Hooray,&nbsp;we&nbsp;have&nbsp;a&nbsp;widget!<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;<\/pre>\n<h2>Where Do Widget Factories Come From?<\/h2>\n<p>To enable construction of <code>Widget<\/code> objects, we built a <code>WidgetFactory<\/code>, so to enable construction of <code>WidgetFactory<\/code> objects, we&#8217;ll build a <code>WidgetFactoryFactory<\/code>. Then, to enable construction of those&#8230; Ha! Just kidding. \ud83d\ude09<\/p>\n<p>Each activatable runtime class is defined in a module (DLL). Each module that defines one or more activatable runtime classes must export an entry point named <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br205771.aspx\"><code>DllGetActivationFactory<\/code><\/a>. It is declared as follows:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\"><span style=\"color: #2b91af\"> &nbsp;&nbsp;&nbsp;HRESULT<\/span>&nbsp;<span style=\"color: #6f008a\">WINAPI<\/span>&nbsp;DllGetActivationFactory(<span style=\"color: #2b91af\">HSTRING<\/span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">activatableClassId<\/span>,\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">IActivationFactory<\/span>**&nbsp;<span style=\"color: gray\">factory<\/span>);<\/pre>\n<p>This function is, in a sense, a factory for activation factories: it takes as an argument the name of a runtime class (<code>activatableClassId<\/code>) and it returns via the out parameter <code>factory<\/code> an instance of the activation factory for the named type. If the module does not have an activation factory for the named type, it returns a failure error code. (<em>Aside: <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br205775.aspx\"><code>HSTRING<\/code><\/a> is the Windows Runtime string type, which we&#8217;ll discuss in a future article.<\/em>)<\/p>\n<p>Conceptually, we can think of the function as being implemented like so:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">HRESULT<\/span>&nbsp;<span style=\"color: #6f008a\">WINAPI<\/span>&nbsp;DllGetActivationFactory(<span style=\"color: #2b91af\">HSTRING<\/span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">activatableClassId<\/span>,\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">IActivationFactory<\/span>**&nbsp;<span style=\"color: gray\">factory<\/span>)\n&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Convert&nbsp;the&nbsp;HSTRING&nbsp;to&nbsp;a&nbsp;C&nbsp;string&nbsp;for&nbsp;easier&nbsp;comparison:<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">wchar_t<\/span>&nbsp;<span style=\"color: blue\">const<\/span>*&nbsp;className&nbsp;=&nbsp;WindowsGetStringRawBuffer(<span style=\"color: gray\">activatableClassId<\/span>,&nbsp;<span style=\"color: blue\">nullptr<\/span>);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Are&nbsp;we&nbsp;being&nbsp;asked&nbsp;for&nbsp;the&nbsp;Widget&nbsp;factory?&nbsp;&nbsp;If&nbsp;so,&nbsp;return&nbsp;an&nbsp;instance:<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">if<\/span>&nbsp;(wcscmp(className,&nbsp;L<span style=\"color: #a31515\">\"WidgetComponent.Widget\"<\/span>)&nbsp;==&nbsp;0)\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*<span style=\"color: gray\">factory<\/span>&nbsp;=&nbsp;Make&lt;<span style=\"color: #2b91af\">WidgetFactory<\/span>&gt;().Detach();\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;<span style=\"color: #6f008a\">S_OK<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;If&nbsp;our&nbsp;module&nbsp;defines&nbsp;other&nbsp;activatable&nbsp;types,&nbsp;we'd&nbsp;check&nbsp;for&nbsp;them&nbsp;here.<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: green\">\/\/&nbsp;Otherwise,&nbsp;we&nbsp;return&nbsp;that&nbsp;we&nbsp;failed&nbsp;to&nbsp;satisfy&nbsp;the&nbsp;request:<\/span>\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*<span style=\"color: gray\">factory<\/span>&nbsp;=&nbsp;<span style=\"color: blue\">nullptr<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;<span style=\"color: #6f008a\">E_NOINTERFACE<\/span>;\n&nbsp;&nbsp;&nbsp;&nbsp;}<\/pre>\n<p>In practice, we should never have to do much work to implement this function. When C++\/CX is used to build a component, the compiler will implement this function automatically if the <code>_WINRT_DLL<\/code> macro is defined (this macro is defined by default in the Windows Runtime Component project template in Visual Studio). With WRL, a bit of work is required, but it&#8217;s quite straightforward. Each activatable class must be registered with WRL using one of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/hh700142.aspx\">the <code>ActivatableClass<\/code> macros<\/a>. For example, to register our <code>Widget<\/code> type with its <code>WidgetFactory<\/code> activation factory, we can use the <code>ActivatableClassWithFactory<\/code> macro:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #6f008a\">ActivatableClassWithFactory<\/span>(<span style=\"color: #2b91af\">Widget<\/span>,&nbsp;<span style=\"color: #2b91af\">WidgetFactory<\/span>)\n<\/pre>\n<p>Because many types only permit default construction, and because default construction makes use of the <code>IActivationFactory<\/code> interface and doesn&#8217;t require any custom, type-specific logic, WRL also provides a helpful form of this macro, <code>ActivatableClass<\/code>. This macro generates a simple activation factory that allows default construction, and registers the generated activation factory. We used this macro in Part 1 when we translated the <code>Number<\/code> class from C++\/CX into WRL.<\/p>\n<p>If all of the activatable runtime classes are registered with WRL, we can simply have <code>DllGetActivationFactory<\/code> delegate to WRL and let WRL do all of the hard work.<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\"><span style=\"color: #2b91af\"> &nbsp;&nbsp;&nbsp;HRESULT<\/span>&nbsp;<span style=\"color: #6f008a\">WINAPI<\/span>&nbsp;DllGetActivationFactory(<span style=\"color: #2b91af\">HSTRING<\/span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: gray\">activatibleClassId<\/span>,\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">IActivationFactory<\/span>**&nbsp;<span style=\"color: gray\">factory<\/span>)\n    {\n&nbsp;&nbsp;    &nbsp;&nbsp;<span style=\"color: blue\">auto<\/span>&nbsp;&amp;module&nbsp;=&nbsp;Microsoft::WRL::<span style=\"color: #2b91af\">Module<\/span>&lt;Microsoft::WRL::<span style=\"color: darkslategray\">InProc<\/span>&gt;::GetModule();\n&nbsp;&nbsp;    &nbsp;&nbsp;<span style=\"color: blue\">return<\/span>&nbsp;module.GetActivationFactory(<span style=\"color: gray\">activatibleClassId<\/span>,&nbsp;<span style=\"color: gray\">factory<\/span>);\n    }\n<\/pre>\n<p>At this point, we have everything that we need to make a runtime class constructible: we have a factory that can construct instances of our runtime class and we have a well-defined way to obtain the factory for any activatable runtime class, so long as we know the module in which that runtime class is defined.<\/p>\n<h2>Creating an Instance<\/h2>\n<p>We&#8217;ve finished implementing our activatable runtime class; now let&#8217;s take a look at <code>ref new<\/code> and what happens when we create a <code>Widget<\/code> instance. At the beginning of this article, we started off with the following:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">Widget<\/span>^&nbsp;widget&nbsp;=&nbsp;<span style=\"color: blue\">ref<\/span>&nbsp;<span style=\"color: blue\">new<\/span>&nbsp;<span style=\"color: #2b91af\">Widget<\/span>(42);&nbsp;\n<\/pre>\n<p>We can translate this into the following C++ code that uses WRL instead of C++\/CX:<\/p>\n<pre style=\"background: white;color: black;font-family: Consolas\">&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">HStringReference<\/span>&nbsp;classId(RuntimeClass_WidgetComponent_Widget);\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">IWidgetFactory<\/span>&gt;&nbsp;factory;\n&nbsp;&nbsp;&nbsp;&nbsp;RoGetActivationFactory(\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;classId.Get(),\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">__uuidof<\/span>(<span style=\"color: #2b91af\">IWidgetFactory<\/span>),\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: blue\">reinterpret_cast<\/span>&lt;<span style=\"color: blue\">void<\/span>**&gt;(factory.GetAddressOf()));\n&nbsp;&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color: #2b91af\">ComPtr<\/span>&lt;<span style=\"color: #2b91af\">IWidget<\/span>&gt;&nbsp;widget;\n&nbsp;&nbsp;&nbsp;&nbsp;factory-&gt;CreateInstance(42,&nbsp;widget.GetAddressOf());<\/pre>\n<p>Instantiation is a two-step process: first we need to get the activation factory for the <code>Widget<\/code> type, then we can construct a <code>Widget<\/code> instance using that factory. These two steps are quite clear in the WRL code. <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/br224648.aspx\"><code>RoGetActivationFactory<\/code><\/a> is a part of the Windows Runtime itself. It:<\/p>\n<ol>\n<li>finds the module that defines the named runtime type,<\/li>\n<li>loads the module (if it hasn&#8217;t already been loaded),<\/li>\n<li>obtains a pointer to the module&#8217;s <code>DllGetActivationFactory<\/code> entry point,<\/li>\n<li>calls that <code>DllGetActivationFactory<\/code> function to get an instance of the activation factory,<\/li>\n<li>calls <code>QueryInterface<\/code> on the factory to get a pointer to the requested interface, and<\/li>\n<li>returns the resulting interface pointer.<\/li>\n<\/ol>\n<p>Most of these are straightforward and require no further comment. The exception is the first item: how, exactly, does the Windows Runtime determine which module to load to instantiate a particular type? While there is a requirement that the <em>metadata<\/em> for a type be defined in a WinMD file whose name is similar to the type name, there is no such requirement for the naming of modules: the <code>Widget<\/code> type may be defined in any module.<\/p>\n<p>Every Windows Store app contains a file named AppXManifest.xml. This manifest contains all sorts of important information about the app, including its identity, name, and logo. The manifest also contains a section containing <em>extensions<\/em>: this section contains a list of all of the modules that define activatable types and a list of all of the activatable types defined by each of those modules. For example, the following entry is similar to what we would find for the <code>Widget<\/code> type:<\/p>\n<pre><code>&nbsp;&nbsp;&nbsp;&nbsp;&lt;Extension Category=\"windows.activatableClass.inProcessServer\"&gt;<br \/> <\/code><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;InProcessServer&gt;<br \/> <\/code><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;Path&gt;WidgetComponent.dll&lt;\/Path&gt;<br \/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ActivatableClass ActivatableClassId=\"WidgetComponent.Widget\" ThreadingModel=\"both\" \/&gt;<br \/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;\/InProcessServer&gt;<br \/> &nbsp;&nbsp;&nbsp;&lt;\/Extension&gt; <\/code><\/pre>\n<p>The list includes only types defined by modules contained in the app package; types provided by Windows (i.e., types in <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/apps\/br211377.aspx\">the Windows namespaces<\/a>) are registered globally, in the registry, and are not included in the AppXManifest.xml manifest.<\/p>\n<p>For most projects, this manifest is created as part of the app packaging task that runs after an app is built. The contents of the extensions section is automatically populated via examination of the WinMD files for any referenced components and the manifests from any referenced <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/hh768146.aspx\">Extension SDKs<\/a>. When our app calls <code>RoGetActivationFactory<\/code>, the Windows Runtime uses this list to find the module it needs to load for the <code>Widget<\/code> type.<\/p>\n<p>It should be noted that, for performance, activation factories may be cached on both sides of the ABI boundary: our component that defines the <code>Widget<\/code> type really only needs to create a single instance of the <code>WidgetFactory<\/code>; it doesn&#8217;t need to create a new instance every time it is asked for the factory. Similarly, our app can cache the factory it got back from <code>RoGetActivationFactory<\/code> to avoid having to round-trip through the runtime every time it needs to construct a <code>Widget<\/code>. If our app creates lots of <code>Widget<\/code>s, this may make a huge difference. Both WRL and C++\/CX are pretty smart with respect to this caching.<\/p>\n<h2>In Conclusion<\/h2>\n<p>It suffices to say that the C++\/CX syntax hides a substantial amount of complexity! We started off with what were effectively four lines of C++\/CX: two lines to declare the constructors, and two statements to demonstrate use of those constructors. We have ended up with, well, an awful lot more than that. For the two constructors, we have a <code>Widget<\/code>-specific factory interface, an activation factory that implements that interface and the <code>IActivationFactory<\/code> interface, and a module entry point that creates factories. For the <code>ref new<\/code> expressions, we have a round-trip through the Windows Runtime infrastructure.<\/p>\n<p>Note that everything described here applies to the general case of defining a constructible type in one module and instantiating that type from another module. That is, this is the mechanism for constructing objects through the ABI. If the type is defined in the same module as the code that is instantiating the type, the compiler is able to avoid much of the overhead that is required for calls across the ABI boundary. &nbsp;A future article will discuss how things work within a single module, but know that things are often much simpler in that case.<\/p>\n<p>If you&#8217;ve found these articles useful, we&#8217;d love to hear from you in the comments! &nbsp;Let us know if you have any questions, ideas, or requests, either about this series of articles or about C++\/CX in general. &nbsp;You can also follow me on Twitter&nbsp;(<a href=\"https:\/\/twitter.com\/JamesMcNellis\">@JamesMcNellis<\/a>), where I tweet about a wide range of C++-related topics.<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/UnderConstructionSolution.zip\">UnderConstructionSolution.zip<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>See C++\/CX Part 0 of [n]: An Introduction for an introduction to this series and a table of contents with links to each article in the series. In this article, we&#8217;ll take a look at the how runtime classes are constructed. We&#8217;ll use the following Widget runtime class throughout this article: &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;ref&nbsp;class&nbsp;Widget&nbsp;sealed &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;public: &nbsp;&nbsp;&nbsp;&nbsp; [&hellip;]<\/p>\n","protected":false},"author":282,"featured_media":35994,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[121,132,160],"class_list":["post-2143","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cplusplus","tag-ccx","tag-windows-8","tag-windows-store-apps"],"acf":[],"blog_post_summary":"<p>See C++\/CX Part 0 of [n]: An Introduction for an introduction to this series and a table of contents with links to each article in the series. In this article, we&#8217;ll take a look at the how runtime classes are constructed. We&#8217;ll use the following Widget runtime class throughout this article: &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;ref&nbsp;class&nbsp;Widget&nbsp;sealed &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;public: &nbsp;&nbsp;&nbsp;&nbsp; [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/2143","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/users\/282"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/comments?post=2143"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/2143\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media\/35994"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media?parent=2143"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/categories?post=2143"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/tags?post=2143"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}