我正在尝试 Marshal.AllocHGlobal 并发现令人费解的是这段代码不会成功,而是会引发 OutOfMemory 异常:
namespace HAlloc
{
using System;
using System.IO;
using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
// large file ~ 800MB
string fileName = @"largefile.bin";
FileInfo fileInfo = new FileInfo(fileName);
// allocation succeeds
IntPtr p = Marshal.AllocHGlobal((int)fileInfo.Length);
// OutOfMemory exception thrown here:
Marshal.Copy(File.ReadAllBytes(fileName), 0, p, (int)fileInfo.Length);
Marshal.FreeHGlobal(p);
}
}
}
为什么 AllocHGlobal 调用成功时会出现 OutOfMemory?