Writing a Windows 8 Metro Hello World app using C#, XAML, and calling into a C++ component

Sunday, August 5, 2012


Windows 8 and the new WinRT promises fluid interoperability between C#, C++, and HTML/Javascript. Today we'll take a quick look at a Hello World app built using C# and XAML calling into a C++ component.

First, create a new blank C#/XAML app and call it HelloInterop:

Visual Studio 2012 New Project dialog

Next, add a new project to this solution:

Adding new project to existing solution

Choose the C++ Windows Runtime Component project type and call it HelloCpp.

New Project dialog with C++ selected

Finally, right click on the C# HelloInterop project in the Solution Explorer and choose "Add Reference..." then add the C++ component as a reference (you may have to choose "Solution" on the left pane first):

Adding project reference to project in same solution

Now, we'll work on the C++ code. Open up Class1.h. (Feel free to rename it, but for this guide we'll just stick with this name.) Notice that it's a public ref class and is contained within a namespace — this is required if this class is to be visible to external consumers. Let's add a simple function. Add this line under the constructor's declaration:

Platform::String^ ConcatString(Platform::String^ a, Platform::String^ b);

Now open Class1.cpp and implement this function by adding this code to the bottom of the file:

String^ Class1::ConcatString(String^ a, String^ b)
{
    return String::Concat(a, b);
}

To make the app call this function, let's add a TextBlock to the main page. Open MainPage.xaml and add this line to the page inside the Grid:

<TextBlock Name="CppTextBlock"/>

In MainPage.xaml.cs, add some code inside OnNavigatedTo() to set the text of this element:

var c = new HelloCpp.Class1();
this.CppTextBlock.Text = c.ConcatString("Hello ", "World");

Now run the app and you should see "Hello World" on your screen.

Tags: metro, winrt, csharp, cplusplus, xaml | Posted at 19:50 | Comments (0)


Comments

There are no comments.

Add a comment

Name:
Email: (optional, not displayed to public)
URL: (do not fill this in — leave blank!)

Comment: