This article describes how to convert a hosted Extension from system: string * To char * in Visual C ++. net.
Method 1
PtrtostringcharsSpecifies an internal pointer to the actual string object. If you pass this pointer to an unmanaged function call, you must first lock the pointer to ensure that the object will not be moved during asynchronous garbage collection:
//#include <vcclr.h>System::String * str = S"Hello world/n";const __wchar_t __pin * str1 = PtrToStringChars(str);wprintf(str1);
Method 2
StringtohglobalansiCopy the content of the hosted String object to the local heap and dynamically convert it to the ANSI format. This method will allocate the required local heap memory:
//using namespace System::Runtime::InteropServices;System::String * str = S"Hello world/n";char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);printf(str2);Marshal::FreeHGlobal(str2);
Method 3
Vc7CstringClass has a constructor that carries a hosted string pointer and loads its content to cstring:
//#include <atlstr.h>System::String * str = S"Hello world/n";CString str3(str); printf(str3);
Complete code example
//compiler option:cl /clr #include <vcclr.h>#include <atlstr.h>#include <stdio.h>#using <mscorlib.dll>using namespace System;using namespace System::Runtime::InteropServices;int _tmain(void){System::String * str = S"Hello world/n";//method 1const __wchar_t __pin * str1 = PtrToStringChars(str);wprintf(str1);//method 2char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);printf(str2);Marshal::FreeHGlobal(str2);//method 3CString str3(str); printf(str3);return 0;}
Original address: http://support.microsoft.com /? Id = 311259