Convert a 'System::String ^' to 'const char *' in vc++

人走茶凉 提交于 2019-12-03 07:55:39

It's like this: How to convert from System::String* to Char* in Visual C++

System::String ^ str = "Hello world\n";

//method 1
pin_ptr<const wchar_t> str1 = PtrToStringChars(str);
wprintf(str1);  

//method 2
char* str2 = (char*)Marshal::StringToHGlobalAnsi(str).ToPointer();
printf(str2);
Marshal::FreeHGlobal((IntPtr)str2);

//method 3
CString str3(str); 
wprintf(str3);

//method 4
#if _MSC_VER > 1499 // Visual C++ 2008 only
marshal_context ^ context = gcnew marshal_context();
const char* str4 = context->marshal_as<const char*>(str);
puts(str4);
delete context;
#endif
devan

This is work for me.

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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!