.Net程序突破2G的内存访问限制的方法(3)
1、为当前进程申请锁定内存的权限(注意 调用进程的帐号必须具备锁定内存的权限,否则这一步会失败)
2、就是需要申请的页面数量
3、通过 AllocateUserPhysicalPages API 申请AWE内存
以下为引用的内容:
public AweStream(UInt32 capacity)
{
unsafe
{
// Enable the privilege of lock memory.
lock (_SetLockPagesPrivilegeLockObj)
{
if (!_SetLockPagesPrivilegeOk)
{
LoggedSetLockPagesPrivilege.SetLockPagesPrivilege(System.Diagnostics.Process.GetCurrentProcess(), true);
_SetLockPagesPrivilegeOk = true;
}
}
General.SYSTEM_INFO sysInfo;
General.GetSystemInfo(out sysInfo); // fill the system information structure
_PageSize = sysInfo.dwPageSize;
if ((capacity % _PageSize) != 0)
{
_NumberOfPages = capacity / _PageSize 1;
}
else
{
_NumberOfPages = capacity / _PageSize;
}
_PFNArraySize = (UInt32)(_NumberOfPages * sizeof(UInt64*)); // memory to request for PFN array
_PFNArray = Marshal.AllocHGlobal((int)_PFNArraySize);
UInt32 numberOfPagesInitial = _NumberOfPages;
if (!AweApi.AllocateUserPhysicalPages(System.Diagnostics.Process.GetCurrentProcess().Handle,
ref _NumberOfPages, _PFNArray))
{
Dispose();
throw new AweStreamException("Cannot allocate physical pages", AweStreamException.Reason.CannotAllocatePhysicalPages);
}
_AweAllocated = true;
if (numberOfPagesInitial != _NumberOfPages)
{
Dispose();
throw new AweStreamException(string.Format("Allocated only {0} pages.", _NumberOfPages),
AweStreamException.Reason.AweMemoryNotEnough);
}
_Capacity = _PageSize * _NumberOfPages;
}
}
AWE内存申请完毕后并不能被立即访问到,我们必须将其映射到32位内存地址中才可以访问。
下面是内存映射的代码:
也很简单: