Author Archives: JamesMcNellis

“printf” debugging in Metro style apps

Visual Studio has lots of great debugging features, but sometimes it’s easiest to trace program behavior using “printf” debugging. This can be a bit tricky when writing a Metro style app (you may have noticed that a Metro style app doesn’t have a console window!), so let’s consider a few of our options.

The “supported” way to do this is to use OutputDebugString to write messages to the debug console. This function is callable from within a Metro style app. While useful, it is quite limited: it does no formatting, and is effectively equivalent to the std::puts Standard Library function. If we want to do formatting, we must either do so ourselves before calling OutputDebugString, or write a set of helpers to do the formatting for us. Ick.

Another option would be to configure std::cout to write its output to the debug console via OutputDebugString. It’s fairly straightforward to do this using Boost’s tee_device; see, for example, the answers to the Stack Overflow question “Capturing cout in Visual Studio 2005 output window?”

That’s still a bit more work than we’d like to have to do, not everyone uses Boost, and often it’s nice to have a real console window with which we can interact. While a Metro style app doesn’t start off with a console window, we can create one ourselves.

In Windows, if an application wants to create a console window, it calls the AllocConsole function, which “allocates a new console for the calling process.” We can see in the documentation that it “Applies to: desktop apps only.” This means that, among other things,

  • When we include <Windows.h>, this function will be omitted; its declaration will be #ifdef‘ed out.

  • If we call this function in our program, it will fail WACK certification. Since we only want to use this for debugging or testing, that’s not a problem.

  • There are no guarantees as to the behavior of the function when called from a Metro style app. Technically, if a Metro style app calls the function, the app exhibits undefined behavior.

Note that none of these restrictions mean that we can’t call the function from a Metro style app, it just takes a bit of work to do so and in theory, it might not work (or it might fail unexpectedly or catastrophically). In practice, this particular function appears to work fine, though of course your mileage may vary. Since we’re only suggesting using this for debugging or testing, there is little risk if things go awry.

Here’s a simple example of how you might go about using a console from a Metro style app:

// Include Windows.h for WINBASEAPI and WINAPI:
#include <Windows.h>

// Declare AllocConsole ourselves, since Windows.h omits it:
extern "C" WINBASEAPI int WINAPI AllocConsole();

auto main(Platform::Array<Platform::String^>^) -> int
{
    AllocConsole();

    std::wcout << L"Hello there!" << std::endl;
    std::getchar();

    return EXIT_SUCCESS;
}

This program behaves as you might expect: it creates a console window, prints Hello there!, then awaits user input on the console. This same technique for creating a console window is used in the CxxReflect unit tests so that unit tests that require the Windows Runtime may share much of the same code that is used to drive unit tests that can run in a normal Win32 process.

In a real Metro style app, we might consider calling AllocConsole from the constructor of our App type or in the dynamic initializer of a namespace-scope variable, depending on how early we need to be able to write things to the console.

CxxReflect: Native Reflection for the Windows Runtime

[Note: Apparently the code snippets are rendered incorrectly in Internet Explorer 10. If they appear without linebreaks, please try viewing the article in Internet Explorer 9, Chrome, or Firefox. My apologies for any inconvenience.]

CxxReflect is a native reflection library for use with the Windows Runtime, implemented in C++. The source is hosted on CodePlex at http://cxxreflect.codeplex.com and is licensed under the Boost Software License. This post gives an introduction to the library and provides a broad overview of the features of the library. Future posts (and eventually, documentation on CodePlex) will describe individual features in greater detail.

If you are not familiar already with the Windows Runtime, I’d highly recommend Martyn Lovell’s Lang.NEXT talk, The Windows Runtime, and Deon Brewis’s //BUILD/ talk, “Under the covers with C++ for Metro style apps”. Ian Griffiths’s blog posts, “Real Native WinRT Development” and “Native WinRT Inheritance,” are also great reads.


The CxxReflect library is divided into three parts (very much like Gaul):

  1. A metadata reader (in the CxxReflect::Metadata namespace), that loads assemblies, decodes the metadata tables, parses function and type signatures, and performs other low-level translation.

  2. A read-only reflection API (in the CxxReflect namespace) that provides access to the type system. Most of the classes are very similar to the .NET Reflection API. For example, there are Type, Method, and Parameter classes.

  3. Integration with the Windows Runtime (in the CxxReflect::WindowsRuntime namespace). This part uses the Windows Runtime APIs to discover types available in a Windows Runtime application. It provides utilities for inspecting runtime objects and for dynamically invoking methods and instantiating objects.

There is nothing Windows Runtime-specific in the first two parts; they are written in portable C++ and can be used to read ordinary .NET assemblies. The Windows Runtime integration will only build on Windows 8 and can only be used from a packaged Windows Runtime application. It works equally well with both “low-level” C++ and “high-level” C++ (a.k.a. C++/CX or C++-with-hats).

All of the following examples (and many of the test programs in the library source) use the namespace cxr for brevity. This namespace is an alias for both CxxReflect and CxxReflect::WindowsRuntime.


Getting type information and enumerating types

The most basic use case for Reflection is: given an object, we’d like to find out what its type is:

Platform::Object^ instance = GetInstanceOfAnObject();
cxr::Type const type = cxr::GetTypeOf(instance);

Alternatively, perhaps we know the name of a type and we’d like to get some type information for it:

cxr::Type const type = cxr::GetType(L"Windows.UI.Xaml.Controls.Button");

We can also search for types that match a particular criteria. For example, we can search for all of the types of dependency objects:

typedef Windows::UI::Xaml::IDependencyObject IDependencyObject;
auto const types = cxr::GetImplementersOf<IDependencyObject>();

There are a few limitations to what types can be inspected. In short, if you want to be able to get information about or use a type, you’ll need to make sure that

  • the type is public, and
  • the type is implemented in a Windows Runtime Component (i.e., for C++, a DLL).

Private types are not present in the metadata (WinMD), and types defined in an EXE are not instantiable by CxxReflect.


Creating some objects

It’s not very useful to get information from objects if we can’t do anything with that information, so let’s create some objects.

If you pull the source from CodePlex, you’ll find the WRLibrary test project, which defines the following interface and a handful of runtime classes that implement it and return different values:

public interface class IProvideANumber
{
    default::int32 GetNumber();
};

We’ll also use this PrintTypeAndNumber utility function in the examples that follow:

void PrintTypeAndNumber(WRLibrary::IProvideANumber^ const provider)
{
    std::wstringstream formatter;
    formatter << cxr::GetTypeOf(provider).GetFullName() << L":  "
              << provider->GetNumber() << L'\n';
    OutputDebugString(formatter.str().c_str());
}

The following example enumerates all of the runtime classes that implement IProvideANumber, instantiates each class, and prints the type of the object and the value it returns from GetNumber():

auto const types(cxr::GetImplementersOf<WRLibrary::IProvideANumber>());
std::for_each(begin(types), end(types), [&](cxr::Type const& type)
{
    if (!cxr::IsDefaultConstructible(type))
        return;

    auto const instance(cxr::CreateInstance<WRLibrary::IProvideANumber>(type));

    PrintTypeAndNumber(instance);
});

If you run the test app, you’ll see that this prints:

WRLibrary.ProviderOfZero:  0
WRLibrary.ProviderOfOne:  1
WRLibrary.ProviderOfTheAnswer:  42

You’ve probably noticed that we cheated: we skipped any types that are not default-constructible. Why? Well, for starters, we didn’t provide any arguments to CreateInstance.

It is possible to instantiate a type using a constructor other than its default constructor. The WRLibrary also has a UserProvidedNumber type that is not default constructible. Its sole constructor has an integer parameter; it returns the provided integer from calls to GetNumber(). The following example creates a few instances of this type:

cxr::Type const type(cxr::GetType(L"WRLibrary.UserProvidedNumber"));
for (int i(0); i < 3; ++i)
{
    auto const instance(cxr::CreateInstance<WRLibrary::IProvideANumber>(type, i));

    PrintTypeAndNumber(instance);
}

This example will print:

WRLibrary.UserProvidedNumber:  0
WRLibrary.UserProvidedNumber:  1
WRLibrary.UserProvidedNumber:  2

Actually, that really doesn’t look very exciting. Certainly not much more exciting than default construction. However, the process of creating an object with arguments is significantly more complex. The Windows Runtime provides a handy function that we can use to default-construct an object, but to instantiate an object with arguments we have to:

  1. enumerate the constructors of the type,
  2. perform (limited) overload resolution to select the right constructor,
  3. convert the arguments to the parameter types,
  4. compute the actual address of the constructor, and
  5. call the constructor and return the newly created object.

The logic implemented to enable this also lays the groundwork for being able to dynamically invoke any member function of any runtime object. Currently, only instantiation is supported, but eventually CxxReflect will support invocation of arbitrary member functions. Note that, at least for the moment, dynamic invocation can only be used on x86 and x64 (not ARM), and there are some limitations on what types may be passed as arguments.


What’s next?

CxxReflect is a work in progress and there are many incomplete or unimplemented features. Most notably, generics are not well-supported and support for events and properties is still unimplemented. As noted above, the infrastructure is in place to enable dynamic invocation of arbitrary member functions, but there is no user-friendly interface for that yet. Finally, performance tuning has thus far taken a back seat to “make things work,” so some functionality is noticeably slow.

I’m interested, though, to hear how people might find this useful and what sorts of libraries or applications people might be interested in building with this. Several people have already suggested a few uses, but I’m definitely interested to hear about what other ideas people might have. If you don’t want to leave a comment, feel free to drop me an e-mail (james@jamesmcnellis.com).