Tuesday, April 09, 2013 3:54 PM
Build a Windows Runtime Component for Windows Phone 8 and pass it a String
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:
- Create your Windows Phone 8 app in C# or VB
- Add an additional project using the Windows Runtime Component template.
- 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)
i = ValueData -> Length();
Note two key things:
- The parameter is defined of type Platform::String^
- 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!