C# IntPtr 与 string互转/char*与string互转/char* 与 IntPtr互转/string与byte[]互转

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;

string转成 Base64 形式的String

//byte[] 转string
byte[] b = Encoding.Default.GetBytes("字符串");
//byte[]转成 Base64 形式的String
string a = Convert.ToBase64String(b);

Base64 形式的String转成string

//Base64形式的String转成byte[]
byte[] c= Convert.FromBase64String(a_str);
//byte[]转String
String d = System.Text.Encoding.Default.GetString(c);

IntPtr与byte[]互转

IntPtr转byte[]

int size = 30;
byte [] managedArray = new byte[size];
Marshal.Copy(pBuffer, managedArray, 0, size);

//byte[]转IntPtr
byte [] managedArray = {1,2,3,4,5 };
int size = Marshal.SizeOf(managedArray [0])* managedArray.Length;
IntPtr pBuffer= Marshal.AllocHGlobal(size);

posted @ 2021-12-16 15:46  devdog  阅读(2243)  评论(0编辑  收藏  举报