System::String^ 转换为 char*

使用 Visual C++ .NET 中的托管扩展从 System::String^ 转换为 char* 的若干方法。 
https://msdn.microsoft.com/zh-cn/library/2x8kf7zx.aspx

方法 1


StringToHGlobalAnsi  将托管 String 对象的内容复制到本机堆,然后动态地将它转换为美国国家标准学会 (ANSI) 格式。此方法将分配所需的本机堆内存:
//using namespace System::Runtime::InteropServices;
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
printf(str2);
Marshal::FreeHGlobal( IntPtr(str2) );

方法2

VC7  CString  类有一个构造函数,它带有一个托管 String 指针并将其内容加载到 CString 中:
//#include <atlstr.h>
System::String ^ str = "Hello world\n";
CString str3( str ); 
printf(str3);
---------------------------------------   char *  转  String^    ------------------------

const char * p = "你妹的";
String ^ MyStr = Marshal::PtrToStringAnsi((IntPtr)(char *)p);
Console::WriteLine(MyStr);


完整代码示例

//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 = "Hello world\n";	

    //method 1
    char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
    printf(str2);
    Marshal::FreeHGlobal( IntPtr(str2) );
    //method 2
    CString str3(str); 
    printf(str3);
 
   
  const char * p = "你妹的";
  String ^ MyStr = Marshal::PtrToStringAnsi((IntPtr)(char *)p);
  Console::WriteLine(MyStr);
return 0;}

猜你喜欢

转载自blog.csdn.net/wuan584974722/article/details/81016971