jueves, 3 de septiembre de 2015

C++ Platform::String^ object to const wchar_t* conversion

In Windows Store applications, for example when you want to make a shared library, it is necessary to make use of common types like Platform::String. All the public types must be types from Windows Runtime to make it possible a cross language usage of your libraries (C++, JavaScript, C#, VB).

But when you want to use the C++ standard types like wchar_t or std::wstring, you're going to need a temporary conversion from Windows Runtime types to C++ Standard types.

You can access the string value of a Platform::String^ object by using the Data() method like this:

Platform::String^ ps3DModel(L"Gear");
std::wstring _3DModel = ps3DModel->Data();

Now, you can use the _3DModel std::wstring like another C++ standard string by using his own methods. Also, you could have converted to a "const wchar_t type":

const wchar_t * _3DModel = ps3DModel->Data();

The problem is when you want to make any changes into the ps3DModel Platform::String object since this is inmutable. What you mus to do is make a copy of the string into a std::wstring object and them modify it according to your needs. Later, when you must save the changes into the Platform::String object, you must create as a new "ref new Platform::String^". But better, let's see this with a small example:

// We create the Platform::String object
Platform::String^ ps3DModel(L"Gear");

// Now, we copy the string into a new wstring object
std::wstring _3DModel = ps3DModel->Data();

// Here we make some changes
_3DModel = L"_GEAR_";

// An finally, we put the changes into the original 'ps3DModel' object
ps3DModel = ref new Platform::String(_3DModel.c_str());

No hay comentarios:

Publicar un comentario