转换平台::数组<byte>到字符串

Convert Platform::Array<byte> to String

本文关键字:gt 字符串 byte lt 平台 数组 转换      更新时间:2023-10-16

A 在库中C++有一个函数,该函数读取资源并返回Platform::Array<byte>^

如何将其转换为Platform::Stringstd::string

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

我需要dataPlatform::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-16wchar_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 );