首页 > 其他 > 详细

利用Marshal.AllocHGlobal申请非托管内存,unsafe代码

时间:2015-03-25 08:54:18      阅读:170      评论:0      收藏:0      [点我收藏+]
        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;
            }

        }

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

利用Marshal.AllocHGlobal申请非托管内存,unsafe代码

原文:http://www.cnblogs.com/flyant/p/4364630.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!