Category Archives: Uncategorized

C++/WinRT: Working with Namespaces

Previous: Optimizing Activation

The Windows Runtime adopted namespaces as part of its type system. This works rather well since most languages targeting the Windows Runtime support namespaces in a fairly uniform way. Unfortunately, C++ has a bit more history than most languages and that is certainly true when it comes to the Windows platform. The problem is that C++/WinRT was not the first language projection for C++. C++/CX may not have been standard C++, but it exists within the Visual C++ compiler such that it causes problems when porting a project from C++/CX to C++/WinRT and especially when gradually migrating from one to the other. Then there’s the Windows SDK with its own historical complications.

Fortunately, C++/WinRT was designed with all of this in mind. The Windows SDK ships with headers describing the Windows Runtime APIs in standard C++. This is known as an ABI rather than a language projection since its really just a bunch of COM interface declarations and no attempt is made to “project” it into modern C++. I might use the IStringable type as follows:

#include <windows.foundation.h>
using namespace ABI::Windows::Foundation;

IStringable * stringable = ...

HSTRING value = nullptr;
HRESULT hr = stringable->ToString(&value);

Naturally you might want to use smart pointers and handle wrappers here, but that’s not part of the ABI. Notice that the windows.foundation.h header introduces a root ABI namespace in which the “Windows.Foundation.IStringable” type is declared. This is a good thing for the SDK to do. Technically, it’s the MIDL compiler that prepends this lovely disambiguator. C++/WinRT takes much the same approach to namespaces:

#include <winrt/windows.foundation.h>
using namespace winrt::Windows::Foundation;

IStringable stringable = ...

winrt::hstring value = stringable.ToString();

Notice that instead of the ABI root namespace, I’m now using the winrt root namespace. The Windows namespace, or any other namespace found in a Windows Metadata (.winmd) file, will be safely nested within the respective root namespaces. This is significant because it means that you can use the two together in the same project. There’s a way to disambiguate type names.

And then comes C++/CX and it blissfully thinks it lives on an island all on its own:

using namespace Windows::Foundation;

IStringable ^ stringable = ...

Platform::String ^ value = stringable->ToString();

Notice that there’s no root namespace clearly identifying this “Windows” from any other. Here “Windows” is the root namespace. That’s a bit of a drag. There are also various culprits in the Windows SDK, headers that inexplicably chose not to use the ABI root namespace. What to do?

All is not lost. Naturally, if you’re starting a new project then you can just ignore the ABI from the Windows SDK and you can just avoid C++/CX entirely:

using namespace winrt;
using namespace Windows::Foundation;

IStringable stringable = ...

hstring value = stringable.ToString();

Here I start with a using directive, allowing unqualified name lookup for anything in the winrt namespace. This is the simplest and most convenient route. You might still need to include the ABI headers from the Windows SDK. Perhaps to access an interop API not described in Windows metadata. But you must be explicit about it. Simply adding a using directive will not work:

using namespace winrt;
using namespace Windows::Foundation;
using namespace ABI::Windows::Foundation; // error!

The compiler will tell you that the ABI namespace is ambiguous. That’s because the winrt namespace itself includes its own ABI representation in the winrt::ABI namespace. You might try to be explicit as follows:

using namespace winrt;
using namespace Windows::Foundation;
using namespace ::ABI::Windows::Foundation;

IStringable stringable = ... // error!

But that won’t work either. Now the IStringable type name is ambiguous since that name could refer to either winrt::Windows::Foundation::IStringable or ABI::Windows::Foundation::IStringable.

The same problem occurs when mixing C++/CX with C++/WinRT or the Windows SDK for that matter. This is certainly not a problem that C++/WinRT introduced. One solution is just to be explicit:

winrt::Windows::Foundation::IStringable stringable = ...

While that works, it’s far from convenient. Another solution is to create namespace aliases for the different islands and use those instead:

namespace cx
{
    using namespace ::Windows::Foundation;
}

namespace sdk
{
    using namespace ::ABI::Windows::Foundation;
}

namespace winrt
{
    using namespace Windows::Foundation;
}

I can now unambiguously refer to the IStringable representation from all three type systems in a single program quite conveniently:

int main()
{
    cx::IStringable ^ hat = ...
    sdk::IStringable * pointer = ...
    winrt::IStringable value = ...
}

Any additional namespaces can easily be added as required:

namespace winrt
{
    using namespace Windows::Foundation;
    using namespace Windows::Web::Syndication;
}

Again, this is only required for backward compatibility and in a few other relatively rare cases where you might need to interop between these disparate manifestations of the Windows Runtime APIs.

Join me next time as we continue to explore C++/WinRT. Give C++/WinRT a try today. Got a question? Post it here and we’ll do our best to help.

C++/WinRT: Optimizing Activation

Previous: Fun with Agility

Activation and agility have a strange relationship. In the last installment, I talked about agility, but agility also has an impact on activation. When I talk about activation I mean those things that the language projection (any language projection) must do in order to interact with runtime classes. This might be calling some constructor like this:

using namespace Windows::UI::Xaml::Media;

FontFamily font(L"Consolas");

Or it might be calling some static method like this:

using namespace Windows::UI::Xaml;

Window window = Window::Current();

In either case, activation is at play. That’s because in both cases, the activation factory for the runtime class must be retrieved. In the first example, the “Windows.UI.Xaml.Media.FontFamily” activation factory is what actually creates the FontFamily object under the hood. In the second example, it is the “Windows.UI.Xaml.Window” activation factory that actually implements the “Current” property.

Optimizing activation is all about making the retrieval of the activation factory as efficient as possible. James and I talked about how this is done in this presentation at CppCon 2016. The gist of it is that if the activation factory is agile then it can simply be cached via a magic static. Of course, if the activation factory is not agile then it would not be safe to do so since that would allow the factory object to be accessed from a different apartment to the one in which it was created.

Activation factories should be agile, but sadly some are not. Caching agile activation factories is safe since the cached pointer may be used by any thread from any apartment. Non-agile activation factories may only be used by threads from the same apartment and the overhead of managing a per-apartment cache is prohibitive. Non-agile activation factories are also the source of a variety of bugs. We are moving to a world where all activation factories will be agile. This is the most reliable and efficient model, but we need this fallback in C++/WinRT to deal with existing non-agile factories.

One of the nice things about C++/WinRT is that it is a header-only library. That means you can step into those constructors and static methods above and see how they map to the underlying WinRT plumbing. In both cases, you’ll see that they eventually call this function:

template <typename Class, typename Interface = Windows::Foundation::IActivationFactory>
Interface get_activation_factory()
{
    static Interface factory = impl::get_agile_activation_factory<Class, Interface>();

    if (!factory)
    {
        return impl::get_activation_factory<Class, Interface>();
    }

    return factory;
}

How this function is implemented is an implementation detail but you can clearly see what’s going on. The internal get_agile_activation_factory function will only return a valid factory object if the factory implements the IAgileObject interface. This check is done on demand and once per process. Due to the proliferation of required interfaces and static members in the Windows Runtime, the ability to optimize activation factory access is vital in building high-performance apps and components. As we illustrated at CppCon, the approach taken by C++/WinRT performs substantially better than C++/CX. I have also successfully campaigned within Microsoft to have all activation factories eventually becoming agile. This will provide significant performance wins for both existing and new apps targeting the Windows platform. The good news is that there’s nothing you need to do to opt in to this performance. C++/WinRT will give you the best possible performance today and your apps will only get faster as more of the Windows Runtime switches to agile activation factories.

Join me next time as we continue to explore C++/WinRT. Give C++/WinRT a try today. Got a question? Post it here and we’ll do our best to help.

C++/WinRT: Fun with Agility

Previous: Working with Implementations

For the most part, every COM and WinRT object should be agile. This is a good default unless you have a compelling reason to require an object to reside in a given single-threaded apartment. This typically has to do with reentrancy requirements. Increasingly, APIs that provide services for building user experiences are offering objects that are agile. This tends to provides the best performance and avoids all kinds of problems. Certainly, if you’re implementing an activation factory you must ensure that it is agile even if the runtime class is not. So how does C++/WinRT help or support working with agility?

Here’s a simple example of an implementation:

using namespace Windows::Foundation;

struct Sample : implements<Sample, IStringable>
{
    hstring ToString()
    {
        return L"Sample";
    }
};

This implementation is agile by default. What that means is that unless you say otherwise, the implements class template will implement both IAgileObject and IMarshal. The latter simply uses CoCreateFreeThreadedMarshaler to do the right thing for legacy code that doesn’t know about IAgileObject. So how does one check for agility?

com_ptr<IAgileObject> agile = sample.as<IAgileObject>();

The as method will throw an exception if the sample object is not agile (the query for IAgileObject failed). To avoid the exception, you can use try_as instead:

com_ptr<IAgileObject> maybe = sample.try_as<IAgileObject>();

if (maybe)
{
    // yep, sample is agile!
}

Of course, the IAgileObject interface has no methods beyond those inherited from IUnknown. So, it’s more typical that you might write code like this:

if (sample.try_as<IAgileObject>())
{
    // yep, sample is agile!
}

You see, the IAgileObject interface is just a “marker” interface. The success or failure of the query tells you something. The interface itself is useless. What if you really don’t want an agile implementation? No problem, you can simply request that when you define your implementation:

struct Sample : implements<Sample, non_agile, IStringable>
{
    ...
};

Now, if you run the following check it will report that the object is not agile:

if (sample.try_as<IAgileObject>())
{
    printf("I'm agile :)\n");
}
else
{
    printf("I'm not agile :(\n");
}

And it doesn’t matter where in the variadic parameter pack non_agile appears:

struct Sample : implements<Sample, IStringable, IClosable, non_agile>
{
    ...
};

Of course, this doesn’t preclude you from implementing IMarshal yourself. You might use non_agile to avoid the default agility implementation and then go and implement IMarshal yourself, perhaps to support marhal-by-value semantics.

Now what if you have some poor object that’s not agile but you need to pass it around in some potentially agile context? No problem, the agile_ref helpers comes to the rescue:

IStringable sample = make<Sample>();

You can wrap it inside an agile_ref as follows:

agile_ref<IStringable> ref = sample;

The ref object may be freely passed to a thread in a different apartment:

co_await resume_background();

IStringable local = ref.get();

hstring value = local.ToString();

The get method returns a proxy that may safely be used within the thread context in which the get method was called.

I hope that helps. Join me next time as we continue to explore C++/WinRT. Give C++/WinRT a try today. Got a question? Post it here and we’ll do our best to help.

C++/WinRT: Working with Implementations

Previous: Consumption and Production

Consider the following simple class that implements both the IStringable interface and the IClosable interface. These interfaces were chosen for their simplicity and don’t hold any special status in C++/WinRT (unlike C++/CX).

using namespace Windows::Foundation;

struct Sample : implements<Sample, IStringable, IClosable>
{
    hstring ToString()
    {
        return L"Sample";
    }

    void Close()
    {
    }
};

Clearly this class implements IStringable and IClosable but how do I go from an implementation to an IStringable or IClosable object that I can use or return as part of the projection? There are actually a few options. I alluded to the make function template in the previous installment. The make function returns the first interface implemented by Sample:

IStringable a = make<Sample>();

This is most useful if I’m passing the result directly to a caller. Alternatively, I can specify another interface that the implementation provides:

IClosable b = make<Sample, IClosable>();

Sometimes I might need to get the implementation right away and only later return an interface to some caller. In that case, the make_self function template is what I need:

com_ptr<Sample> c = make_self<Sample>();

Notice that I’ve effectively stepped out of the projection. The Sample class is not part of the projection. It’s my implementation, but I can certainly call its implementation methods directly (without the overhead of a virtual function call):

com_ptr<Sample> c = make_self<Sample>();
hstring h = c->ToString();

Even though the ToString method uses the same signature as the projected IStringable method, here I’m calling that non virtual method directly without crossing the ABI. Since the com_ptr simply holds a pointer to the Sample class, I can also access any other internal details of the implementation.

Finally, if I have an interface and I happen to know that it’s my implementation then I can get back to the implementation using the to_impl function template:

IStringable a = make<Sample>();

Sample * impl = to_impl<Sample>(a);

hstring h = impl->ToString();

Again, this can be used to avoid vcalls and get directly at the implementation but the original object still holds the reference. So if I want to hold on to it I might want to do something like this:

com_ptr<Sample> impl;
impl.copy_from(to_impl<Sample>(a));

The copy_from function will ensure that AddRef is called.

This is just a few of the ways you can interact with and manage implementations. Join me next time as we continue to explore C++/WinRT. Give C++/WinRT a try today. Got a question? Post it here and we’ll do our best to help.

C++/WinRT: Consumption and Production

Previous: Getting Started

Whenever I’m introducing C++/WinRT I often end up talking about consumption and production of Windows Runtime interfaces. This is one of the defining features of C++/WinRT in terms of delivering productivity and reliability for both app and component developers, folks that are consuming and producing Windows Runtime APIs using standard C++.

Consider where we’ve come from. Let’s use the Windows.Foundation.IStringable interface as an example. A classic COM developer wanting to implement or produce a COM interface might write code that looks something like this:

#include "winrt/Windows.Foundation.h"
 
using namespace winrt;
using ABI::Windows::Foundation::IStringable;

struct Produce : implements<Produce, IStringable>
{
    HRESULT __stdcall abi_ToString(HSTRING * value) noexcept override
    {
        return WindowsCreateString(L"Hello world", 11, value);
    }
};

Already this is considerably simpler than it would otherwise be given that the implements class template does a lot of the heavy lifting, efficiently implementing IUnknown, IInspectable, IAgileObject, IWeakReferenceSource, and more. But I’m still left with having to implement the ToString virtual function, concern myself with error handling, and worry about the lifetime and nuances of various ABI types. A classic COM developer wanting to consume such a COM interface would likewise have to write code that looks something like this:

com_ptr<IStringable> s = make<Produce>();

HSTRING value = nullptr;
HRESULT hr = s->abi_ToString(&value);

if (hr != S_OK)
{
    // pain and suffering
}

printf("%ls\n", WindowsGetStringRawBuffer(value, nullptr));
WindowsDeleteString(value);

Again, this is simpler than it would otherwise be as I’m relying on the com_ptr class template and the make function template but I’m still left with some grungy error handling that is fraught with danger.

It is first and foremost these challenges and complications that disappear when you embrace C++/WinRT for consuming and producing Windows Runtime APIs with standard C++. Implementing the IStringable interface enters the world of modern C++:

using namespace winrt;
using Windows::Foundation::IStringable;

struct Produce : implements<Produce, IStringable>
{
    hstring ToString()
    {
        return L"Hello world";
    }
};

Notice the ABI interface is gone as I instead implement the projected IStringable interface with its ToString method that simply returns a lowercase hstring, a value types that takes care of deleting itself when it goes out of scope. No HRESULTs, no concern about exception handling, no awkward ABI functions for creating a string. A C++/WinRT developer can likewise use the same projected IStringable interface to consume such an interface quite simply:

IStringable s = make<Produce>();

hstring value = s.ToString();
printf("%ls\n", value.c_str());

The signature used to implement the ToString method is the same signature used to consume or call it. There’s no need for com_ptr and there’s no error handling or explicit resource management to worry about. This is the abstraction that sits at the heart of C++/WinRT and powers much of the rest of the language projection. This simplicity, an embrace of modern ISO C++, is what makes C++/WinRT such a groundbreaking tool for the Windows developer.

Join me next time as we continue to explore C++/WinRT. Give C++/WinRT a try today. Got a question? Post it here and we’ll do our best to help.

C++/WinRT: Getting Started

With the recent public release of C++/WinRT, I thought I would start writing a few short “how to” and “how it works” articles to help developers understand some of the fundamental principles of the C++ language projection for the Windows Runtime. If you’re wondering what C++/WinRT is or need a more detailed introduction I can suggest the following resources:

moderncpp.com – The original home of C++/WinRT includes all the motivating demos, examples and white papers.

C++/WinRT with Kenny Kerr – My interview on CppCast.

Our CppCon talks on C++/WinRT:

Embracing Standard C++ for the Windows Runtime (Slides)

Putting Coroutines to Work with the Windows Runtime (Slides)

With that, let’s get started. You can download the latest public release here:

https://github.com/microsoft/cppwinrt

One option is to clone the git repository (you can also download it as a ZIP file):

git clone https://github.com/Microsoft/cppwinrt.git

Cloning into 'cppwinrt'...
remote: Counting objects: 1499, done.
remote: Total 1499 (delta 0), reused 0 (delta 0), pack-reused 1499
Receiving objects: 100% (1499/1499), 3.20 MiB | 530.00 KiB/s, done.
Resolving deltas: 100% (663/663), done.
Checking connectivity... done.
Checking out files: 100% (1465/1465), done.

You should now have a folder called cppwinrt that contains your own copy of the repository:

dir /b cppwinrt

10.0.14393.0
Docs
Getting Started.md
license.txt
media
README.md

The 10.0.14393.0 folder represents a build or projection of C++/WinRT for the Windows 10 build 14393 SDK (RS1). Within that folder are actually two folders:

dir /b cppwinrt\10.0.14393.0

Samples
winrt

The winrt folder contains the actual projection, the header-only library that you need to #include to use C++/WinRT. The Samples folder contains a few Visual C++ projects to get you started. Let’s start with a simple app just to make sure everything’s working:

type HostNames.cpp

You can then make sure it builds using the Visual C++ compiler as follows:

cl HostNames.cpp /I cppwinrt\10.0.14393.0 /EHsc /std:c++latest

Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

HostNames.cpp
Microsoft (R) Incremental Linker Version 14.00.24215.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:HostNames.exe
HostNames.obj

The output should be something like this:

HostNames.exe

HOSTNAME
192.168.1.25

Join me next time as we continue to explore C++/WinRT. Got a question? Post it here and we’ll do our best to help.

Getting Started with Modules in C++

Visual Studio 2015 Update 1 shipped with experimental support for a module system for C++. You can learn about it from this talk given by Gabriel Dos Reis at CppCon. Creating and consuming modules is very simple, but getting started with the compiler is not that obvious. At least it wasn’t very obvious to me, so here’s a quick introduction to get you started.

Start by creating an interface source file:

C:\modules>type dog.ixx

#include <stdio.h>

module dog;

export namespace dog
{
    void woof()
    {
        printf("woof!\n");
    }
}

You can use an extension other than .ixx but then you need to tell the compiler that this is the interface to your module. Anything included before the module declaration is not part of the module’s interface but rather merely an implementation detail. So this module will export the dog namespace and its woof function. Nothing else. Go ahead and compile it as follows:

C:\modules>cl -experimental:module -c dog.ixx

Notice the module switch enables support for modules, much like the await switch enables support for coroutines. And since we’re not building an executable, the -c switch instructs the compiler not to involve the linker just yet. The compiler dutifully emits the module artifacts:

C:\modules>dir /b dog.*
dog.ifc
dog.ixx
dog.obj

The .ifc file contains the metadata for the module. The compiler also produces an .obj file that is used to link the module to produce an executable. I can now write an app that relies on this module:

C:\modules>type app.cpp

import dog;

int main()
{
    dog::woof();
}

The import directive tells the compiler to look for the dog module and the main function can call the woof method without having to include any additional declarations. That’s pretty awesome! Compiling the app is also quite straitghtforward:

C:\modules>cl -experimental:module app.cpp dog.obj

The compiler, with the help of the linker this time, successfully imports, compiles, and links the application:

C:\modules>dir /b app.*
app.cpp
app.exe
app.obj

The app prints woof:

C:\modules>app.exe
woof!

There are a variety of other compiler switches to control search paths and other defaults, but this should get you started with modules in Visual C++ 2015 Update 1. Enjoy!

Update: The Visual C++ team just posted a more detailed description.