将String ^转换为wstring C++

Kip*_*k08 3 string c++-cli wstring visual-studio-2012

我用C++编写了一个小应用程序.UI中有一个ListBox.我想使用ListBox的选定项目作为算法,我只能使用wstrings.

总而言之,我有两个问题: - 我可以如何转换我的

    String^ curItem = listBox2->SelectedItem->ToString();
Run Code Online (Sandbox Code Playgroud)

到一个wstring测试?

- 代码中的^是什么意思?

非常感谢!

Ben*_*igt 11

应该这么简单:

std::wstring result = msclr::interop::marshal_as<std::wstring>(curItem);
Run Code Online (Sandbox Code Playgroud)

您还需要头文件来完成这项工作:

#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>
Run Code Online (Sandbox Code Playgroud)

这个marshal_as专业化内部看起来像是好奇的:

#include <vcclr.h>
pin_ptr<WCHAR> content = PtrToStringChars(curItem);
std::wstring result(content, curItem->Length);
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为System::String它在内部存储为宽字符.如果你想要一个std::string,你必须用例如执行Unicode转换WideCharToMultiByte.方便,marshal_as为您处理所有细节.