转换平台::数组<byte>到字符串
Convert Platform::Array<byte> to String
A 在库中C++有一个函数,该函数读取资源并返回Platform::Array<byte>^
如何将其转换为Platform::String
或std::string
BasicReaderWriter^ m_basicReaderWriter = ref new BasicReaderWriter()
Platform::Array<byte>^ data = m_basicReaderWriter ("file.txt")
我需要data
的Platform::String
如果你的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 );
与std::string
不同,Platform::String
包含Unicode UTF-16(wchar_t
)字符串,所以你需要从包含ANSI字符串的原始字节数组转换为Unicode字符串。可以使用 ATL 转换帮助程序类 CA2W
(包装对 Win32 API MultiByteToWideChar()
的调用)执行此转换。然后,您可以使用Platform::String
构造函数获取原始 UTF-16 字符指针:
Platform::String^ str = ref new String( CA2W( data->begin() ) );
注意:我目前没有可用的VS2012,所以我还没有使用C++/CX编译器测试过这段代码。如果您遇到一些参数匹配错误,您可能需要考虑reinterpret_cast<const char*>
从 data->begin()
返回的byte *
指针转换为char *
指针(以及类似的data->end()
),例如
std::string s( reinterpret_cast<const char*>(data->begin()), data->Length );