【问题标题】:convert standard C++ string to String^将标准 C++ 字符串转换为字符串^
【发布时间】:2012-01-26 03:15:51
【问题描述】:

我想在 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());

我的代码出了什么问题?

【问题讨论】:

  • 这两段代码没有做同样的事情:MarshalStringString ^ s 转换为wstring,而您的sn-p 从string 转换为String ^ s(即另一个方式)。
  • 您尝试的问题是 System::Char 是 16 位值,但 char 是 Visual C++ 是 8 位值。

标签: string visual-c++ c++-cli stdstring


【解决方案1】:

Microsoft 为他们的 C++ Suppport Library 提供 Visual Studio 以促进 C++ 和 C++/CLI 之间的交互。该库提供了模板函数marshal_as,它将为您将std::string 转换为System::String^

#include <msclr\marshal_cppstd.h>

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

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 2014-02-05
    • 2011-03-31
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    相关资源
    最近更新 更多