转换标准 C++字符串到字符串^
我想在 Visual C++ 环境中将 std::string 转换为 System::String^ 。我知道我们可以通过 MarshalString
函数将 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));
}
我找不到将 std::string 转换为 System::String 的方法,但我发现System::String 的构造函数的参数如下:
System::String(Char* value, Int32 startIndex, Int32 length)
我尝试使用如下代码,但它不能给我一个正确的解决方案:
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
我的代码中发生了什么错误?
I want to convert to std::string to System::String^ in Visual C++ environment. I know that we can convert System::String to std::string by the MarshalString
Function as below:
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));
}
I can't find the way to convert std::string to System::String but I found that System::String has constructor with argument as below :
System::String(Char* value, Int32 startIndex, Int32 length)
and i try to use code like below, but it can not give me a correct solution :
std::string str1 = "MyString";
System::String^ str = new System::String(str1.c_str(), 0, str1.length());
What wrong happen in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Microsoft 提供其 C++ 支持库 Visual Studio 促进 C++ 和 C++/CLI 之间的交互。该库提供模板函数
marshal_as< /code>
将为您将
std::string
转换为System::String^
:Microsoft provide their C++ Suppport Library with Visual Studio to facilitate interaction between C++ and C++/CLI. That library provides the template function
marshal_as
which will convert astd::string
to aSystem::String^
for you: