问题描述
var cpuInfo: processor_info_array_t = nil
var numCpuInfo: mach_msg_type_number_t = 0
var coresTotalUsage: Float = 0.0
var numCPUsU: natural_t = 0
let err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numCPUsU, &cpuInfo, &numCpuInfo);
assert(err == KERN_SUCCESS, "Failed call to host_processor_info")
我正在调用上面的C API host_processor_info
来从swift快速获取进程负载信息,那里没有问题.cpuInfo
是一个inout参数(指针),返回时将指向包含该API分配的CPU信息的结构.调用方负责分配内存;我可以很容易地从目标C做到这一点,但是没有任何运气.我知道我可以将该调用包装到目标C扩展中,但是我正在尝试快速学习,并且在可能的情况下,希望避免使用obj-c解决方案.
Hi, I am calling the above C API host_processor_info
to get process load informations from swift, no problem there.cpuInfo
is a inout parameter (pointer) that, on return, will point to a structure containing the CPU information allocated by that API.The caller is reponsible for deallocating the memory; I can do that easily from objective C but haven't had any luck in swift. I know I could wrap that call into an objective C extension but I'm trying to learn swift and would like, if possible, avoid the obj-c solution.
在obj-c中,我将使用:
in obj-c I would deallocate with:
size_t cpuInfoSize = sizeof(integer_t) * numCpuInfo;
vm_deallocate(mach_task_self(), (vm_address_t) cpuInfo, cpuInfoSize)
swift中的cpuInfo是一个UnsafeMutablePointer,不能转换为vm_address_t.
cpuInfo in swift is an UnsafeMutablePointer not convertible into a vm_address_t.
任何帮助表示感谢,谢谢.
Any help appreciated, thanks.
推荐答案
processor_info_array_t
是指针类型,而vm_address_t
是整数类型(最终是UInt
的别名). (从<i386/vm_types.h>
中的评论来看这可能是出于历史原因.)在Swift中将指针转换为整数(大小相同)的唯一方法是unsafeBitCast
.
processor_info_array_t
is a pointer type, and vm_address_t
is an integer type(ultimately an alias for UInt
). (Judging from the comments in <i386/vm_types.h>
this might to be for historical reasons.)The only way to convert a pointer to an integer (of the same size) in Swift is unsafeBitCast
.
mach_init.h
定义
extern mach_port_t mach_task_self_;
#define mach_task_self() mach_task_self_
只有extern变量在Swift中可见,在宏中不可见.
Only the extern variable is visible in Swift, not the macro.
这给出了:
let cpuInfoSize = vm_size_t(sizeof(integer_t)) * vm_size_t(numCpuInfo)
vm_deallocate(mach_task_self_, unsafeBitCast(cpuInfo, vm_address_t.self), cpuInfoSize)
这篇关于快速的C数组内存释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!