代码之家  ›  专栏  ›  技术社区  ›  Brian Stewart

在C++/CLI中,在char*和System::String之间转换的最佳方式是什么

  •  40
  • Brian Stewart  · 技术社区  · 16 年前

    在C++/CLI中,从char*到System::string再转换回System::string的认可方式是什么?我找到了一些关于杜元帅的参考资料<&燃气轮机;Google上的模板化功能,但这项功能似乎从未在VisualStudio2005中出现过(AFAIK,VisualStudio2008中也没有)。我还看到了一些关于 Stan Lippman's blog ,但这是从2004年开始的。我还看到了Marshal::StringToHGlobalAnsi()。是否有被视为“最佳实践”的方法?

    5 回复  |  直到 10 年前
        1
  •  74
  •   marsh    7 年前

    字符串有一个接受char*的构造函数:

     using namespace system;
     const char* charstr = "Hello, world!";
     String^ clistr = gcnew String(charstr);
     Console::WriteLine(clistr);
    

     IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
     char *pNewCharStr = static_cast<char*>(p.ToPointer());
     cout << pNewCharStr << endl;
     Marshal::FreeHGlobal(p);
    
        2
  •  18
  •   Matthew Clendening    16 年前

    这里有一个很好的概述(为VS2008添加了此封送支持): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx

        3
  •  0
  •   Dan Blair    16 年前

        4
  •  0
  •   dko    13 年前

    我创建了一些助手方法。我需要这样做,才能从旧的Qt库移动到CLI字符串。如果有人能补充一下,告诉我我是否有内存泄漏,以及我能做些什么来修复它,我将不胜感激。

    void MarshalString (  String ^ s, wstring& os ) {
        using namespace Runtime::InteropServices;
        const wchar_t* char = (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
        os = char;
    }
    QString SystemStringToQt( System::String^ str)
    {
        wstring t;
        MarshalString(str, t);
        QString r = QString::fromUcs2((const ushort*)t.c_str());
        return r;
    }
    
        5
  •  -1
  •   Tadej Mali    11 年前

    另一个链接指向可能的方法摘要:

    http://support.microsoft.com/?kbid=311259