After having spent the better part of a day discovering how to build a simple C++ library for a Windows Phone 8 app, I thought I’d share.

The few couple steps are relatively easy:

  1. Create your Windows Phone 8 app in C# or VB
  2. Add an additional project using the Windows Runtime Component template.
  3. Add a reference to your second (WinRT) component to your managed project using the Add Reference dialog.

The tricky part comes when you want to start passing strings around.  All the Microsoft documentation tells you all about how to pass numbers, Enums, etc. but nothing, not even on StackOverflow about passing strings.

The key is using the Platform namespace in your unmanaged code.  In my case I wanted to pass in a string and return a number.  The key is to discover there’s support for managed strings but you have to know where to look.

First, declare your method in the .h file of your C++ class like this:

int GetNumberFromString(Platform::String^ ValueData);

and then define the method in the .cpp file of your C++ class like this:

int WindowsPhoneRuntimeComponent::GetNumberFromString(Platform::String^ ValueData)
{
    int i;
    i = ValueData -> Length();

    return i;
}

 

Note two key things:

  1. The parameter is defined of type Platform::String^
  2. The parameter is a pointer to a string object, thus you must use the –> operator to reference it’s methods, such as Length() in the example above.

One final thing, to access the string contents, call the Data method which returns a pointer to type const wchar_t.

Hopefully this saves somebody a few hours someday!