将Platform::Array<byte>转换为字符串

3

我有一个C++库中的函数,可以读取资源并返回Platform::Array<byte>^

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

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

我需要从 data 中获取一个 Platform::String


对于 std::string,我想至少它与迭代器对构造函数兼容。 - chris
文件的编码是什么? - svick
1个回答

4
如果你的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() 的调用)来执行此转换。 然后,您就可以使用接受原始 UTF-16 字符指针的 Platform::String 构造函数:
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 );

不能直接在WinRT中使用STL是一种复杂情况。 - ppaulojr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接