利用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;
            }

        }

申请了一个较大的内存块,通过指针来控制数据代码段。如果在方法体内,是无法直接申请到这么大的内存的。

posted on 2015-03-25 07:47  飞翔蚂蚁  阅读(1649)  评论(0编辑  收藏  举报

导航