解释你自己的答案:这不是 Objective-C 代码,而是普通的旧 C,使用 Mach API 来从内核获取统计信息。Mach API 是由 XNU 导出的低级 API,它是一个混合内核,由顶层(导出 BSD API,就像我们从 UN*X 熟悉和喜爱的常用系统调用一样)和底层(即 Mach)组成。该代码使用马赫“主机”抽象,它(除其他外)提供有关操作系统级别资源利用率的统计信息。
具体来说,这是一个完整的注释:
#import <mach/mach.h> // Required for generic Mach typedefs, like the mach_port_t
#import <mach/mach_host.h> // Required for the host abstraction APIs.
extern "C" // C, rather than objective-c
{
const int HWUtils_getFreeMemory()
{
mach_port_t host_port;
mach_msg_type_number_t host_size;
vm_size_t pagesize;
// First, get a reference to the host port. Any task can do that, and this
// requires no privileges
host_port = mach_host_self();
host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
// Get host page size - usually 4K
host_page_size(host_port, &pagesize);
vm_statistics_data_t vm_stat;
// Call host_statistics, requesting VM information.
if (host_statistics(host_port, // As obtained from mach_host_self()
HOST_VM_INFO, // Flavor - many more in <mach/host_info.h>(host_info_t)&vm_stat, // OUT - this will be populated
&host_size) // in/out - sizeof(vm_stat).
!= KERN_SUCCESS)
NSLog(@"Failed to fetch vm statistics"); // log error
/* Stats in bytes */
// Calculating total and used just to show all available functionality
// This part is basic math. Counts are all in pages, so multiply by pagesize
// Memory used is sum of active pages, (resident, used)
// inactive, (resident, but not recently used)
// and wired (locked in memory, e.g. kernel)
natural_t mem_used = (vm_stat.active_count +
vm_stat.inactive_count +
vm_stat.wire_count) * pagesize;
natural_t mem_free = vm_stat.free_count * pagesize;
natural_t mem_total = mem_used + mem_free;
NSLog(@"used: %u free: %u total: %u", mem_used, mem_free, mem_total);
return (int) mem_free;
}