简体   繁体   English

转换Platform :: Array <byte> 到String

[英]Convert Platform::Array<byte> to String

A have a function in C++ from a library that reads a resource and returns Platform::Array<byte>^ A在C ++中有一个来自库的函数,该库读取资源并返回Platform::Array<byte>^

How can I convert this into a Platform::String or an std::string 如何将其转换为Platform::Stringstd::string

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

I need a Platform::String from data 我需要一个来自dataPlatform::String

If your Platform::Array<byte>^ data contains an ASCII string (as you clarified in a comment to your question), you can convert it to std::string using proper std::string constructor overloads (note that Platform::Array offers STL-like begin() and end() methods): 如果您的Platform::Array<byte>^ data包含ASCII字符串(正如您在问题的注释中阐明的那样),您可以使用正确的std::string构造函数重载将其转换为std::string (请注意Platform::Array提供类似STL的begin()end()方法):

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

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

Unlike std::string , Platform::String contains Unicode UTF-16 ( wchar_t ) strings, so you need a conversion from your original byte array containing the ANSI string to Unicode string. std::string不同, Platform::String包含Unicode UTF-16wchar_t )字符串,因此您需要从包含ANSI字符串的原始字节数组转换为Unicode字符串。 You can perform this conversion using ATL conversion helper class CA2W (which wraps calls to Win32 API MultiByteToWideChar() ). 您可以使用ATL转换助手CA2W (包装对Win32 API MultiByteToWideChar()调用MultiByteToWideChar()执行此转换。 Then you can use Platform::String constructor taking a raw UTF-16 character pointer: 然后你可以使用Platform::String构造函数获取原始的UTF-16字符指针:

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

Note: I currently don't have VS2012 available, so I haven't tested this code with the C++/CX compiler. 注意:我目前没有VS2012可用,所以我没有用C ++ / CX编译器测试这段代码。 If you get some argument matching errors, you may want to consider reinterpret_cast<const char*> to convert from the byte * pointer returned by data->begin() to a char * pointer (and similar for data->end() ), eg 如果你得到一些匹配错误的参数,你可能需要考虑reinterpret_cast<const char*>data->begin()返回的byte *指针转换为char *指针(类似于data->end() ) ,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM