托管指针转换指针
原创2023年6月15日小于 1 分钟
Intptr与指针转换,涉及两个方法Marshal.AllocHGlobal和Marshal.FreeHGlobal,他们成对出现。
提示
注意勾选项目属性里的不安全代码
using System.Runtime.InteropServices;
int a = 1;
Console.WriteLine(a);
unsafe
{
IntPtr a_ptr = Marshal.AllocHGlobal(a * sizeof(byte));
byte* c = (byte*)a_ptr.ToPointer();
*c = 2;
Marshal.FreeHGlobal(a_ptr);
Console.WriteLine(*c);
}
Console.WriteLine(a);
//输出
//1
//2
//1