C# IntPtr 与 string互转

一、IntPtr 与 string互转

string str = "aa";

IntPtr init = Marshal.StringToHGlobalAnsi(str);

string ss= Marshal.PtrToStringAnsi(init);

//最后释放掉

Marshal.FreeHGlobal(init);  

二、char*与string互转

 string a = "11";      

 char* aChar = (char*)System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(a).ToPointer(); 

string result = Marshal.PtrToStringAnsi((IntPtr)aChar);   

三、char* 与 IntPtr互转

可以直接强制类型转换

IntPtr init = (IntPtr)aChar;

char* aChar = (char*)init;

你可能感兴趣的:(C#笔记)