45

在 C++/CLI 中从 char* 转换为 System::string 并返回的批准方法是什么?我在 Google 上找到了一些对 marshal_to<> 模板化函数的引用,但似乎此功能从未适用于 Visual Studio 2005(并且不在 Visual Studio 2008 中,AFAIK)。我还在Stan Lippman 的博客上看到了一些代码,但它是 2004 年的。我还看到了 Marshal::StringToHGlobalAnsi()。有没有一种被认为是“最佳实践”的方法?

4

5 回答 5

75

System::String 有一个接受 char* 的构造函数:

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

找回一个 char* 有点困难,但还不错:

 IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
 char *pNewCharStr = static_cast<char*>(p.ToPointer());
 cout << pNewCharStr << endl;
 Marshal::FreeHGlobal(p);
于 2008-09-11T14:57:34.743 回答
18

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

于 2008-09-11T14:34:28.433 回答
0

我们所做的是创建一个 C++\CLI 对象,该对象将字符串保存在未编辑的代码中,并会给出该项目的管理副本。转换代码看起来很像 Stan 在他的博客上的代码(我记不清了)(如果你使用他的代码,请确保更新它以使用 delete[]),但我们确保析构函数会处理释放所有对象的未管理元素。这有点夸大其词,但是当我们绑定到遗留 C++ 代码模块时,我们没有泄漏。

于 2008-09-11T13:58:17.210 回答
0

我创建了一些辅助方法。我需要这样做才能从旧的 Qt 库迁移到 CLI String。如果有人可以补充这一点并告诉我是否似乎有内存泄漏以及我能做些什么来解决它,我将不胜感激。

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;
}
于 2011-06-01T17:14:19.477 回答
-1

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

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

于 2013-05-25T17:00:01.130 回答