什么是在C++/CLI中从char*转换为System::string的批准方式,然后再转回去的方法?我在Google上找到了一些关于marshal_to<>模板函数的参考资料,但似乎这个功能从未纳入Visual Studio 2005(据我所知,它也不在Visual Studio 2008中)。我还看到过Stan Lippman的博客中的一些代码,但那是2004年的。我还看到了Marshal::StringToHGlobalAnsi()。是否有一种被认为是“最佳实践”的方法?
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);
这里有一个很好的概述(为 VS2008 添加了这种封送支持): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx
#include <msclr\marshal.h> // marshal_context context; // my_c_string = context.marshal_as<const char*>(my_csharp_string);
- gatopeichmsclr::interop::marshal_context
。 - Mugen我创建了一些辅助方法。我需要这样做是为了从旧的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;
}
marshal_context
相比,Marshal::StringToHGlobalAnsi
是一个较差的选择(正如Matthew所提到的),因为它没有使用RAII自动释放缓冲区。更不用说这个名字完全错误,它根本不返回HGLOBAL
。 - Ben Voigtchar *
字符串作为参数来gcnew
一个字符串。也许您可以转换为signed char *
? - Ben Straub