Win32系统中,一个进程可寻址的地址空间是4GB,用户可使用的地址空间是大概是2GB,但这不是说用户可以申请2GB的内存,因为这2GB只是可以使用的“地址”空间,而不是可以使用的“内存”空间,可分配内存的大小还受制于物理内存和磁盘交换文件的大小。因为物理内存和磁盘交换文件是供整个系统和所有用户程序使用的,所有系统内核、当前执行的所用用户程序的代码、数据,以及分配的内存总量并不能超过物理内存和磁盘交换文件的总和。
当设计一个可能需要申请大量内存的程序时,我们就需要预先得知系统的配置情况,这时可以使用GlobalMemoryStatusEx函数。
GlobalMemoryStatusEx函数用来获得系统当前物理内存和虚拟内存的使用情况:
BOOL WINAPI GlobalMemoryStatusEx(
__inout LPMEMORYSTATUSEX lpBuffer //指向MEMORYSTATUSEX结构的指针
);
函数调用成功返回非0值,失败返回0值。
其中MEMORYSTATUSEX结构如下:
typedef struct _MEMORYSTATUSEX {
DWORD dwLength; //本结构长度
DWORD dwMemoryLoad; //已用内存百分比
DWORDLONG ullTotalPhys; //物理内存总量
DWORDLONG ullAvailPhys; //可用物理内存
DWORDLONG ullTotalPageFile; //交换文件总的大小
DWORDLONG ullAvailPageFile; //交换文件中空余部分大小
DWORDLONG ullTotalVirtual; //用户可用地址空间
DWORDLONG ullAvailVirtual; //当前空闲的地址空间
DWORDLONG ullAvailExtendedVirtual; //保留值,设为0
} MEMORYSTATUSEX, *LPMEMORYSTATUSEX;
在调用之前需要首先将dwLength字段设置为MEMORYSTATUSEX结构的长度,当调用GlobalMemoryStatusEx函数后,函数会在结构中返回对应的数值。注意:dwTotalPageFile字段返回的是交换文件的最大值,并不是当前实际建立的交换文件的大小,一般当前的交换文件大小会小于该值,但这个数值的大小也不是确定的,如果需要的话,系统会增加它的大小直到不再有空余的磁盘空间放置交换文件为止。
实例如下:
// Sample output:
// There is 51 percent of memory in use.
// There are 2029968 total Kbytes of physical memory.
// There are 987388 free Kbytes of physical memory.
// There are 3884620 total Kbytes of paging file.
// There are 2799776 free Kbytes of paging file.
// There are 2097024 total Kbytes of virtual memory.
// There are 2084876 free Kbytes of virtual memory.
// There are 0 free Kbytes of extended memory.
#include <windows.h>
#include <stdio.h>
// Use to convert bytes to KB
#define DIV 1024
// Specify the width of the field in which to print the numbers.
// The asterisk in the format specifier "%*I64d" takes an integer
// argument and uses it to pad and right justify the number.
#define WIDTH 7
void main(int argc, char *argv[])
{
MEMORYSTATUSEX statex;
statex.dwLength = sizeof (statex);
GlobalMemoryStatusEx (&statex);
printf ("There is %*ld percent of memory in use./n",
WIDTH, statex.dwMemoryLoad);
printf ("There are %*I64d total Kbytes of physical memory./n",
WIDTH, statex.ullTotalPhys/DIV);
printf ("There are %*I64d free Kbytes of physical memory./n",
WIDTH, statex.ullAvailPhys/DIV);
printf ("There are %*I64d total Kbytes of paging file./n",
WIDTH, statex.ullTotalPageFile/DIV);
printf ("There are %*I64d free Kbytes of paging file./n",
WIDTH, statex.ullAvailPageFile/DIV);
printf ("There are %*I64d total Kbytes of virtual memory./n",
WIDTH, statex.ullTotalVirtual/DIV);
printf ("There are %*I64d free Kbytes of virtual memory./n",
WIDTH, statex.ullAvailVirtual/DIV);
// Show the amount of extended memory available.
printf ("There are %*I64d free Kbytes of extended memory./n",
WIDTH, statex.ullAvailExtendedVirtual/DIV);
}
(注意:GetGlobalMemoryStatus有时会返回错误值,因此建议使用GetGlobalMemoryStatusEx!!)