转换标准 C++字符串到字符串^

发布于 2024-12-22 06:34:45 字数 772 浏览 1 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三五鸿雁 2024-12-29 06:34:45

Microsoft 提供其 C++ 支持库 Visual Studio 促进 C++ 和 C++/CLI 之间的交互。该库提供模板函数 marshal_as< /code>将为您将 std::string 转换为 System::String^

#include <msclr\marshal_cppstd.h>

std::string stdString;
System::String^ systemString = msclr::interop::marshal_as<System::String^>(stdString);

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 a std::string to a System::String^ for you:

#include <msclr\marshal_cppstd.h>

std::string stdString;
System::String^ systemString = msclr::interop::marshal_as<System::String^>(stdString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文