利用Marshal.AllocHGlobal申请非托管内存,unsafe代码
unsafe public class RUN { int[] array3; IntPtr handle; int handleCount = 0; public RUN() { handleCount = 1024 * 2560; handle = System.Runtime.InteropServices.Marshal.AllocHGlobal(handleCount*4); } ~RUN() { System.Runtime.InteropServices.Marshal.FreeHGlobal(handle); } public int run10() { Int32* p = (Int32*)handle; int count = 0; for (int n = 0; n < 500; n++) { for (int i = 0; i < handleCount; i++) { count++; p[i] = i+n; } } return count; } }
申请了一个较大的内存块,通过指针来控制数据代码段。如果在方法体内,是无法直接申请到这么大的内存的。
———— 十年迷茫,不再困惑,下一刻,我就要飞翔 ————