Convert Platform :: Array <byte> to String

A has a function in C ++ from a library that reads a resource and returns Platform::Array<byte>^

How can I convert this to Platform::String

orstd::string

BasicReaderWriter^ m_basicReaderWriter = ref new BasicReaderWriter()
Platform::Array<byte>^ data = m_basicReaderWriter ("file.txt")

      

I need Platform::String

fromdata

+3


source to share


1 answer


If yours Platform::Array<byte>^ data

contains an ASCII string (as you explained in the comment to your question), you can convert it to std::string

using the correct constructor overloads std::string

(note that Platform::Array

STL-like begin()

and suggest end()

):

// Using std::string range constructor
std::string s( data->begin(), data->end() );

// Using std::string buffer pointer + length constructor
std::string s( data->begin(), data->Length );

      

In contrast std::string

, Platform::String

contains UTF-16 ( wchar_t

) Unicode strings , so you need to convert from the original byte array containing the ANSI string to Unicode string. You can perform this conversion using the ATL Conversion Helper class CA2W

(which wraps calls to the Win32 API MultiByteToWideChar()

). Then you can use the constructor Platform::String

using a raw pointer to a UTF-16 character:



Platform::String^ str = ref new String( CA2W( data->begin() ) );

      

Note: I don't have VS2012 at this time, so I haven't tested this code with a C ++ / CX compiler. If you get some matches with the arguments, you might consider reinterpret_cast<const char*>

converting from a pointer byte *

returned data->begin()

to a pointer char *

(and similar for data->end()

), for example

std::string s( reinterpret_cast<const char*>(data->begin()), data->Length );

      

+4


source







All Articles