以编程方式获取OS X上安装的RAM量

Gra*_*erg 5 c++ memory macos iokit

我正在安装一台安装了8 GB内存的机器,我正在尝试以编程方式确定机器中安装了多少内存.我已经尝试使用sysctlbyname()来获取安装的内存量,但它似乎仅限于返回一个带符号的32位整数.

uint64_t total = 0;
size_t size = sizeof(total);
if( !sysctlbyname("hw.physmem", &total, &size, NULL, 0) )
     m_totalMemory = total;
Run Code Online (Sandbox Code Playgroud)

The above code, no matter what type is passed to sysctlbyname, always returns 2147483648 in the total variable. I've been searching through IOKit and IORegistryExplorer for another route of determining installed memory, but have come up with nothing so far. I've found IODeviceTree:/memory in IORegistryExplorer, but there's no field in there for size. I'm not finding anything anywhere else in the IO Registry either. Is there a way to access this information via IOKit, or a way to make sysctlbyname return more than a 32-bit signed integer?

Dav*_*haw 8

您可以使用sysctl()和查询HW_MEMSIZE.这会将内存大小返回为64位整数,而不是默认的32位整数.

手册页给出了详细信息.


Chu*_*uck 7

The easy way:

[[NSProcessInfo processInfo] physicalMemory]
Run Code Online (Sandbox Code Playgroud)

  • 他们不是互相排斥的. (5认同)