Swift pointer problems with MACH_TASK_BASIC_INFO

后端 未结 6 2108
一个人的身影
一个人的身影 2020-12-08 08:58

I am trying to convert an ObjC stackoverflow answer to Swift and failing. It looks like I am passing a UnsafeMutablePointer when I

6条回答
  •  时光取名叫无心
    2020-12-08 09:28

    Nate’s answer is excellent but there’s a tweak you can make to simplify it.

    First, rather than allocating/deallocating the task_basic_info pointer, you can create the struct on the stack, then use withUnsafeMutablePointer to get a pointer directly to it which you can pass in.

    func report_memory() {
        var info = mach_task_basic_info()
        var count = mach_msg_type_number_t(sizeofValue(info))/4
    
        let kerr: kern_return_t = withUnsafeMutablePointer(&info) {
    
            task_info(mach_task_self_,
                task_flavor_t(MACH_TASK_BASIC_INFO),
                task_info_t($0),
                &count)
    
        }
    
        if kerr == KERN_SUCCESS {
            println("Memory in use (in bytes): \(info.resident_size)")
        }
        else {
            println("Error with task_info(): " +
                (String.fromCString(mach_error_string(kerr)) ?? "unknown error"))
        }
    }
    

提交回复
热议问题