April 2014

Volume 29 Number 4


Windows Store : Windows Store C++ for C# Developers: Understanding the Domain

Bill Kratochvil

C# developers have a rich development environment that emphasizes productivity over performance. I suspect this statement might be met with some skepticism from C# developers as performance is excellent and exceeds what most of us need to accomplish our goals. Thus, for C# developers, modern C++ may not offer a return on investment as productivity may suffer even with all of the new improvements the new C++ offers. However, the beauty of Windows Store app development is that you can take an agile approach to building reusable components that’s productive, using the best of both languages to phase in C++ components where they’re most useful.

This article is intended for C# developers who want to tap into the power and performance that modern C++, C++/CX (component extensions), and the Windows Runtime C++ Template Library (WRL) offer (all referred to as C++ here for brevity). It’s also intended for developers who, like me, plan on leveraging the power of the Windows Azure cloud. Applications built with C++ not only have the potential to extend tablet and phone battery life but should also result in lower cost due to better performance per watt, per transistor and per cycle (see “C++ and Beyond 2011: Herb Sutter – Why C++?” at bit.ly/1gtKQya). 

The problem C# developers encounter in attempting to learn C++ is that most of the documentation, blogs and other material available reflect the perspectives of experienced C++ developers, not the C# developer (who generally doesn’t want to build a single-project console application). To further complicate matters, C++ is undergoing a renaissance, so much of the current material could be obsolete, not apply or distract you from the newer, more efficient coding techniques. To discern what’s valid and what isn’t, you need a basic understanding of the domain, indicated by acronyms such as C++, C++/CLI, C++/CX, WRL, STL, ATL, WinRT and so on. Without this understanding you could end up burning valuable cycles learning material that doesn’t apply to your objective, which is, most likely, ramping up quickly to build C++ Windows Store applications. 

My interest in C++ came about when I hit the C# performance ceiling with a use case that had to process a complex algorithm on more than 200,000 records. My research took me to the webcast, “Taming GPU Compute with C++ AMP” (bit.ly/1dajKE6), which presented a demo application that changed my perception of performance forever. Had I had experience with C++ AMP, and been able to create a proof of concept to present to the team, I suspect they would’ve gladly accepted a C++ component when they saw an 11-second process reduced to milliseconds. Unfortunately, the magnitude of C++ information (and disinformation) available, coupled with my lack of C++ domain knowledge, had me stumbling into a vast library of information, searching for the shelf that contained the books pertaining to C++ development for Windows Store applications.

The purpose of this article is not to teach you C++, but to point you to that shelf. This will ensure your learning path is clear, free of muddied waters, and you’re not distracted by the blizzard of information that can actually block your progress and cause you unnecessary frustration. After reading this article, you should be better equipped to benefit from applicable C++ material, such as the more recent MSDN Magazine articles, libraries and blogs about C++ development.

The code download for this article is a Visual Studio solution containing three apps based on different development platforms: C#, C++ and JavaScript. As you’ll see, within this solution I abbreviate Windows Store applications as Wsa for my project names (this is not an official abbreviation). The WsaJavaScript application is based on the MSDN tutorial, “Walkthrough: Creating a Basic Windows Runtime Component Using WRL” (bit.ly/1n1gvV2). You’ll see that I simply added two buttons labeled “Data Binding” and “Data Binding (Reused)” to this tutorial application (as shown in Figure 1). Note that both the WsaXamlCpp (C++/CX) and WsaXamlCs (C#) applications in this solution use the same libraries and yield the same exact results.

Three Application Views
Figure 1 Three Application Views (Applications Shown in Green, Libraries in Purple, Use Cases in Gray)

The C# and C++/CX applications demonstrate just how powerful Windows Store application development really is—you can seamlessly reuse components between platforms, as the right pane of Figure 1 shows). For example, as you review the code, you’ll find both the C# and C++/CX demo applications use the same XAML, which was copied and pasted into each application’s respective view (DataBindingView). Likewise, you’ll see they use the same presenter (DataBindingPresenter), view model (MainViewModel), data access layer (MockDataDal) and logger (DebugLogger). With Windows Store application development, you can create C# or C++ libraries in either language, so you can step into C++ development at your own pace, and replace less efficient C# algorithms with high-performance C++ AMP code with minimal productivity loss.

Productivity shines because you can recycle all of your useful code. For example, the logger for both applications (see the output window at the bottom of Figure 2) is a C# component that resides in the C# WsaWrcCs project. I didn’t have to invest time building a C++ logger, which has negligible impact on performance, and could focus on more critical areas. Figure 2 also reveals there’s little difference between the C# and C++/CX code in the DataBindingPresenter class; this class contains most of the application’s code as all other logic resides in the shared components (you’ll find little code in both application projects).

C++/CX and C# Code Using the Same View Model, Data Access Layer and Logger
Figure 2 C++/CX and C# Code Using the Same View Model, Data Access Layer and Logger

Besides showing off the power of Windows Store application development, the solution presented here provides a sandbox in which you can start C++ development. Where most tutorials and examples provide code for a console app (having little value in a Windows Store application environment), this solution gives you sample code in the applicable project type in which you’re interested—modern C++, WRL or C++/CX. You can see how your C++ code can be easily accessed by the C# application.

While I’m going to discuss the C++ domain topics applicable to Windows Store app development, they won’t be covered in great depth here. However, the following should provide a baseline from which you can continue your research, and I’ll provide some links so you can drill down into the details, when applicable. The point of this exercise is to help you focus on the key topics you need to understand, effectively filtering out the magnitude of information that doesn’t apply. I want to acknowledge the Microsoft C++ development team, as they were instrumental in helping me navigate through the massive library of information to find the shelf I needed so I could be productive in my journey to becoming a Microsoft C++ developer.

Windows Runtime (WinRT)

The WinRT type system lets you use a variety of languages to access Windows APIs (that are exposed as WinRT types) and to write apps and components using the same technology. The Windows Runtime is based on an Application Binary Interface (ABI); a standard for connecting components, as well as APIs.

What you see in Figure 1 is the seamless integration of different development platforms: C#, C++, and C++/CX transparently being used by JavaScript, C# and C++ Windows Store applications. For this to be possible there has to be a standard interface all development languages adhere to so they can use the compiled code.  To achieve this, the WRL and WinRT component projects each generate a .winmd file that serves as a cross-language header file. Note that the .winmd file is essentially a CLI metadata file (so it can be viewed with ILSpy).

You produce and consume the ABI using C++/CX, WRL, C# and JavaScript (or any other language that adds support for the WinRT ABI). As a C# developer your inclination might be to write all of your code using C++/CX, as it’s closest to what you’re accustomed to using,  but you should minimize the use of WinRT as much as possible, and strictly limit it to the ABI layer. For example, your code should leverage the power of C++ using only C++/CX when necessary to cross the ABI. Consistent with its design and purpose, you’ll find that C++/CX contains only a small subset of functions for its components, that is, String will be missing most of the functions to which you’re accustomed and may need, as it was not intended to be a stand-alone development language. Understanding the ABI and its constraints will help you in your C++/CX development. I recommend reviewing the Channel 9 videos on the topic, such as “Under the Covers with C++ for Metro-Style Apps” (bit.ly/1k7CWLq).

Libraries

The Standard Template Library (STL) is the most important library for C++ users. Templates and generics both answer the question, “How do you build type-safe generic containers?” It’s templates in C++ and generics in C#, and though the syntax is somewhat similar, they’re pretty different concepts. Templates are specialized at compile time. Generics are specialized at run time. As for C++/CLI, they’re different enough in that they have different keywords and syntaxes. From a C# perspective, if you approach templates like you do generics you’ll find they’re somewhat familiar. 

As the MSDN Library documentation (bit.ly/1bZzkTB) indicates, the STL establishes uniform standards for the application of iterators to STL containers or other sequences you define, by STL algorithms or other functions you define. This is a common definition of the STL, which means, of course, you’ll need to understand what algorithms, iterators and containers are. I won’t delve into these here, but they’re well documented in the MSDN Library.

Keep in mind the C++ STL isn’t the same thing as the C++ Standard Library. According to MSDN Library documentation, the Standard C++ Library in Visual Studio 2013 is a conforming implementation from which a C++ program can call on a large number of functions. These functions perform essential services such as input and output and provide efficient implementations of frequently used operations (bit.ly/1eQkPlS).

The Active Template Library (ATL) is a set of template-based C++ classes that lets you create small, fast COM objects. It has special support for key COM features, including stock implementations, dual interfaces, standard COM enumerator interfaces, connection points, tear-off interfaces and ActiveX controls (bit.ly/1engnjy). It’s important to know that only a small subset of COM and the WINAPI are supported in a WinRT application. The WRL is better suited for WinRT applications.

The WRL is like a simplified ATL for the Windows Runtime. It consists of a set of headers and templates that can help you develop WinRT classes using standard C++ capabilities. It eliminates a massive amount of boilerplate code you’d otherwise need to add and reduces the line count required to roughly the same as C++/CX. C++/CX is the way most developers are expected to produce and consume WinRT components, unless you need to do so in a code base that bans exceptions or has other special needs, or you simply prefer to avoid proprietary language extensions unless absolutely necessary. WRL is the lowest level of C++ development for interfacing to Windows Store applications. It does lack some facilities for building XAML components, so you should only use C++/CX or C# to create XAML components.

C++

Modern C++ (version 11 or higher) is significantly different from previous versions, outdating many current books, blogs and articles, so be careful. If something is using “new” or “delete,” it’s the old C++. Not that that’s obsolete or useless, and you won’t have to rewrite existing code, as C++11 plays well with existing code; you just won’t be leveraging the simplicity and efficiency of modern C++.

C++/CX is a relatively C# developer-friendly way to author WinRT types. This language extension was created to make it easy to produce and consume WinRT types, but it isn’t required. In fact, you can use WRL to do the same, but not as easily or directly. Note that C++/CX borrows the C++/CLI syntax, but targets a different runtime.

C++/CLI generally isn’t used for Windows desktop development. Typically, it’s used only for managed code in extremely narrow circumstances. For example, some existing native code performs a task well and you want to expose it for easy use from managed code, but the interface you want to expose to managed code isn’t ideally exposed via COM or P/Invoke. The audience for C++/CLI is very, very small. I’ve noted it here only because of the similarities of the ^ (hat) notation and the potential for it to cause confusion as some CLI code samples won’t be compatible with C++/CX.

Both C++/CLI and Windows Store applications written with C++/CX use the hat notation. You can use WinRT components in Windows desktop (not Windows Store) applications with C++/CX, in which case you use the hat. You can also use WinRT components in both Windows Store and Windows desktop applications using C++, in which case the applications won’t use the hat.

When researching the Internet, it’s a good idea to precede your searches with “modern C++” or “C++/CX” to ensure you’ll be viewing applicable documentation.

A History Lesson

In the past, software reusability meant providing access to components without necessarily giving others access to the code. This could be done by providing a static linked library (.lib) file with a header (.h) file, which other developers could then use to link the .lib into different applications—the header provided the interface and the library the compiled sourcecode. 

One of the inherent problems of this practice is the amount of memory and disk space it can take. For example, a 2MB library compiled into a software suite of six applications takes 12MB of disk space. Of course, the average XT-compatible PC disk capacity at the time was 20MB. With the emergence of the DLL came the ability to share a single set of code among multiple applications. With this, the six applications now take only 2MB to use the same library. 

The details, pros and cons of static libraries versus DLLs are outside the scope of this article. You’ll find exhaustive references to both libraries in MSDN Library documentation.

Static libraries and DLLs have a place in building modern C++ libraries. However, if you’re trying to build reusable components that can be easily accessed by JavaScript, C++ and C# Windows Store applications, you need to resist the knee-jerk reaction to select the Windows Store application DLL (to which C# developers are accustomed). As you’ll see later, it’s not the DLL as you know it. Instead, you’ll want to select the project template for the WinRT component (which I refer to as WRC). This is what Microsoft recommends, and it provides a development experience closest to the one to which you’re accustomed.

Project Templates

For C# developers, adding a new library is simple—you add a class library project and use it to build your interfaces, classes and so forth. Referencing class libraries is just as easy, as you simply add references to your class library project from your application or other class libraries—productivity at its best.

Unfortunately, building C++ libraries is far less straightforward and, as of this writing, you won’t find a lot of documentation or examples on how to set up Visual Studio for the development of reusable components, in particular on configuring the various available project template types. The following will help you set up Visual Studio to use the Windows Store application C++ project templates.

WinRT Component

The MSDN Library documentation for “DLLs (C++/CX)” suggests that when you need to create a DLL for a Windows Store app, you should create it as a WinRT component by using the project template of that name (bit.ly/1iwL1Wg). As I noted, this option offers the most familiar experience for adding and referencing libraries.  

As Figure 2 shows, there are a lot of similarities between C++/CX and C#, so C# developers should be able to quickly ramp up to C++. The interesting thing about the WinRT component is that it’s transparent to C# and C++ Windows Store apps, giving C# developers a means to focus on both productivity and performance as the situation dictates. Thus, as I indicated earlier, if you want to reuse an existing C# Logger component in your C++ XAML Windows Store application, all you have to do is port the code into a C# WRC project and you’re done. You can now reference it from both C++ and C# applications (as I’ve done in the sample solution).

Keep in mind that because the ABI does impose some restrictions, such as requiring classes to be sealed, you’ll have to look at development from a new angle, one that emphasizes “composition over abstraction,” which lends itself nicely to building composite applications.

WRL Class Library Project Template

A WRL Class Library project template is a set of user-defined classes built using the WRL. Unfortunately, WRL tutorials and explanations can be quite daunting. As an introduction to WRL and understanding the WRL Class Library project template, I recommend you follow the tutorial “Walkthrough: Creating a Basic Windows Runtime Component Using WRL” (bit.ly/1n1gvV2). You’ll be impressed at how, with just a few lines of code, you can access your C++ code from a JavaScript application by simply adding a reference to the library. This tutorial was the basis for the sample solution I’ve provided.

The tutorial is important for those new to WRL because it also provides an important link for generating a WRL project using the WRL Class Library template. This template includes the necessary information to invoke the MIDL compiler, which processes an IDL file (see bit.ly/1fLMurc for more information). Behind the scenes, the MIDL compiler generates the necessary (hidden) files for the Contoso WRL project, which take care of all the overhead associated with WRL development—contoso_h.h, contoso_i.c and contoso_p.c. As you’ll see from the tutorial, all you have to create are the contoso.idl and contoso.cpp files, which Figure 3 and Figure 4 show, respectively. Note that I added the AddStr(string, string) functionality; it wasn’t part of the tutorial.

Figure 3 Contoso.idl

import "inspectable.idl";
import "Windows.Foundation.idl";
import "ocidl.idl";
#define COMPONENT_VERSION 1.0
namespace Contoso {
  interface ICalculator;
  runtimeclass Calculator;
  [uuid(0be9429f-2c7a-40e8-bb0a-85bcb1749367), 
    version(COMPONENT_VERSION),
    exclusiveto(Calculator)]
  interface ICalculator : IInspectable
  {
    // msdn.microsoft.com/library/jj155856
    // Walkthrough: Creating a Basic Windows Runtime Component Using WRL
    HRESULT Add([in] int a, [in] int b, [out, retval] int* value);
    HRESULT AddStr([in] HSTRING a, [in] 
    HSTRING b, [out, retval] int* value);
  }
  [version(COMPONENT_VERSION), activatable(COMPONENT_VERSION)]
  runtimeclass Calculator
  {
    [default] interface ICalculator;
  }
}

Figure 4 Contoso.cpp

#include "pch.h"
#include "Contoso_h.h"
#include <wrl.h>
#include <string>
#include <memory>
#include "Calculator.h"
using namespace std;
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
namespace ABI {
  namespace Contoso   {
    class Calculator : public RuntimeClass<ICalculator> {
      InspectableClass(RuntimeClass_Contoso_Calculator, BaseTrust)
    public:
      // Use an external C++ Windows Store App DLL to handle strings
      // note: WRL doesn't permit overloading functions
      HRESULT __stdcall AddStr(_In_ HSTRING a, _In_ HSTRING b, _Out_ int* value)
      {
        // Convert HSTRING values into const wchar_t*
        // so you can pass them into C++ DLL
        const wchar_t* buffera = WindowsGetStringRawBuffer(a, nullptr);
        const wchar_t* bufferb = WindowsGetStringRawBuffer(b, nullptr);
        // Instantiate calculator using modern methods – reference        
        // msdn.microsoft.com/library/hh279669
        auto calc = make_shared<WsaDllCpp::Calculator>();
        // Add the string values
        auto val = calc->Add(buffera, bufferb);
        // Assign value
        *value = val;
        return S_OK;
      }
      // msdn.microsoft.com/library/jj155856
      // Walkthrough: Creating a Basic Windows Runtime Component Using WRL
      HRESULT __stdcall Add(_In_ int a, _In_ int b, _Out_ int* value)   {
        if (value == nullptr)
        {
          return E_POINTER;
        }
        *value = a + b;
        return S_OK;
            }
      };
      ActivatableClass(Calculator);
  }
}

As with C# class libraries, using a WRL component from an external project or application simply requires you to add a reference to this project.

Static Libraries

Static libraries are appropriate when you’re rebuilding code using current tools for each project and you want minimal overhead calling into the code. This is the option to choose if you probably won’t be using the exact same binary across multiple projects built at different times.

The compiler needs to know the location of the static library (.lib) and its associated header (.h) in order to successfully link the compiled code into the application. This can be done by right-clicking on the Solution and selecting Common Properties | Project Dependencies and then your project (WsaWrcCpp) from the projects list, and checking the .lib file (WsaLibCpp) as a dependency. Then, right-click on the Project (WsaWrcCpp), select Properties | Common Properties | References | Add New Reference | Solution| Projects, and then choose your .lib file (WsaLibCpp).

You now have to let the project know where to find the .lib projects header file. If you’re running through the sample solution, right-click on the WsaWrcCpp (WRC) project and select Properties | Configuration Properties | C/C++ | General, and set the “Additional Include Directories” to the location of the header file, in this case, that would be $(SolutionDir)WsaLibCpp;<existing paths>.

DLLs

In the downloadable sample solution you’ll find a Windows Store application DLL for a C++ project named WsaDllCpp (as in Figure 2). I used the MSDN Library article, “Walkthrough: Creating and Using a Dynamic Link Library (C++)” (bit.ly/1enxzWc) as a reference. Note that this project is for demonstration purposes only as the use of this DLL has been discouraged (in my correspondence with Microsoft C++ developers and reviewers). I’ve included it because you may need to use existing DLLs in your Windows Store application.

With that in mind, the WsaDllCpp DLL gives the solution Contoso WRL (the WRL Class Library template discussed earlier) with the ability to add two strings together; for example, WsaDllCpp::Calculator::Add(“1000”,“2000”) yields 3000. The following interface code highlights the difference between a C++ DLL over the C# DLL as you know it:

#pragma once
#include <string>
#define WSADLLCPP_API __declspec(dllexport)
namespace WsaDllCpp
{
  class Calculator
  {
  public:
    WSADLLCPP_API int Add(const wchar_t* numberOne, 
      const wchar_t* numberTwo);
    WSADLLCPP_API int Add(int numberOne, int numberTwo);
  };
}

As you can see, there’s a wee bit of overhead associated with making functions visible to external libraries and applications (__declspec). Likewise, the settings required to successfully compile the WsaDllCpp into the application go beyond simply setting a project reference. I had to right-click on the Contoso WRL project and select Properties | Configuration Properties | C/C++ | General, and set the “Additional Include Directories” to the location of the header file. 

C# developers might find adding a reference to a DLL isn’t intuitive, or at least it isn’t what you’re accustomed to, as there’s usually a “reference” link in the project list on which to right-click (which you’ll find in the WRC project). As with the .lib file, to add a reference you’ll have to right-click on the project and then select Add | Reference, and then click the Add new Reference button.

Unlike with C# development, you can’t assume the paths you select will be converted to relative paths—they won’t. It’s best to get used to using the Visual Studio macros to specify your paths. For the previous example I had to set the “Additional Include Directories” to $(SolutionDir)WsaDllCpp; <existing paths>.

Wrapping Up

Once you hone in on that correct bookshelf, you’ll discover a wealth of information (particularly in the MSDN Library), making your learning process more efficient and rewarding. This first step toward a basic understanding of the C++ domain will help you in your research and development of C++ Windows Store applications. There’s just so much information that doesn’t apply (such as legacy C++, MFC, C++/CLI and, for the most part, ATL) that this awareness will prevent you from wasting valuable cycles on material that could take you down a long road to a dead end.

I also recommend you review Kenny Kerr’s MSDN Magazine articles (bit.ly/1iv7mUQ) and Channel 9 (bit.ly/1dFqYjV), as well as Michael B. Mclaughlin’s articles at bit.ly/1b5CDhs. (A valuable resource not listed on this site is his “C# to C++ - A Somewhat Short Guide,” available at bit.ly/MvdZv4.)

If you focus your attention on C++/CX, modern C++ and on using the WinRT component, you’ll be well on your way to achieving your goals in the Windows Store application development environment.


Bill Kratochvil is owner of Global Webnet LLC, an Amarillo, Texas-based company that performs contract software architecture and development. Currently, Kratochvil is on contract with a leading company in the medical industry.

THANKS to the following Microsoft technical experts for reviewing this article: Mohammad Al-Sabt, John Cuyle, Chris Guzak, Frantisek Kaduk, Ben Kuhn and Thomas Petchel. Also, thanks to Steven Southwick.
John Cuyle is a software developer in the Studios Publishing group at Microsoft Studios.  He has over ten years’ experience developing games in C++, and a few more years’ experience playing them.
Ben Kuhn has been a developer at Microsoft for 11 years, working on technologies from printing to clipboard to the Windows Runtime. Most recently, Ben contributed to the design of the C++ language extensions for Windows Runtime and helped create the Windows 8.1 Sample Pack.
Thomas Petchel is a senior content publishing manager for Visual C++, and has been with the team for eight years. He loves C++ for its power, performance, and control, and thinks you should too.
Frantisek Kaduk is a Senior Software Development Engineer  in Microsoft/Skype team with more than 10 years’ experience in .NET. He was a member of the team which developed Skype for Windows 8.x application. He blogs infrequently on http://blogs.msdn.com/b/fkaduk.
Steven Southwick is a .net developer primarily focused on clinical trial enrollment modeling using both Monte Carlo simulation and analytical techniques.