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

时间:2023-03-09 06:01:07
利用Marshal.AllocHGlobal申请非托管内存,unsafe代码
        unsafe public class RUN
{ int[] array3;
IntPtr handle;
int handleCount = ;
public RUN()
{
handleCount = * ;
handle = System.Runtime.InteropServices.Marshal.AllocHGlobal(handleCount*);
} ~RUN()
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(handle);
} public int run10()
{
Int32* p = (Int32*)handle;
int count = ;
for (int n = ; n < ; n++)
{
for (int i = ; i < handleCount; i++)
{
count++;
p[i] = i+n;
}
}
return count;
} }

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