Hos*_*her 1 string c++-cli stdstring visual-c++
我想在Visual C++环境中将std :: string转换为System :: String ^.我知道我们可以通过MarshalStringFunction 将System :: String转换为std :: string,如下所示:
void MarshalString ( String ^ s, string& os ) {
using namespace Runtime::InteropServices;
const char* chars =
(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
Run Code Online (Sandbox Code Playgroud)
我找不到将std :: string转换为System :: String的方法,但我发现System :: String的构造函数带有如下参数:
System::String(Char* value, Int32 startIndex, Int32 length)
Run Code Online (Sandbox Code Playgroud)
我尝试使用下面的代码,但它无法给我一个正确的解决方案:
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
Run Code Online (Sandbox Code Playgroud)
我的代码出了什么问题?
Microsoft 使用Visual Studio 提供其C++ Suppport库,以促进C++和C++/CLI之间的交互.该库提供了模板函数marshal_as,它将a转换std::string为a System::String^:
#include <msclr\marshal_cppstd.h>
std::string stdString;
System::String^ systemString = msclr::interop::marshal_as<System::String^>(stdString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5149 次 |
| 最近记录: |