MACH_ASK_BASIC_INFO的Swift指针问题

5anewei6  于 12个月前  发布在  Swift
关注(0)|答案(8)|浏览(142)

我试图将ObjC stackoverflow的答案转换为Swift,但失败了。看起来我应该传递inout mach_msg_type_number_t的时候却传递了UnsafeMutablePointer<mach_msg_type_number_t>,我似乎无法解决我的问题。从我对Swift指针文档的理解(不多)来看,这些应该是可互换的。?
下面的更多信息。
以下是目标C:

struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);

字符串
这里是我在Swift中所得到的(许多行用于更容易的类型检查)

let name: task_name_t = mach_task_self_
let flavor: task_flavor_t = task_flavor_t(MACH_TASK_BASIC_INFO)
var info: mach_task_basic_info
var size: mach_msg_type_number_t = UnsignedFixed(sizeof(mach_task_basic_info_t))
let kerr = task_info(name, flavor, info as task_info_t, &size)


task_info签名是:

func task_info(target_task: task_name_t, flavor: task_flavor_t, task_info_out: task_info_t, task_info_outCnt: UnsafeMutablePointer<mach_msg_type_number_t>) -> kern_return_t


最后一行的错误是:

Cannot convert the expression's type '(@!lvalue task_name_t, task_flavor_t, task_info_t, inout mach_msg_type_number_t)' to type 'kern_return_t'

7eumitmz

7eumitmz1#

我花了一点时间来更新Airspeed Velocity对最新Swift语法(Swift 3,beta 6)的回答,但以下是我得到的:

func report_memory() {
    var info = mach_task_basic_info()
    let MACH_TASK_BASIC_INFO_COUNT = MemoryLayout<mach_task_basic_info>.stride/MemoryLayout<natural_t>.stride
    var count = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)

    let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
        $0.withMemoryRebound(to: integer_t.self, capacity: MACH_TASK_BASIC_INFO_COUNT) {
            task_info(mach_task_self_,
                      task_flavor_t(MACH_TASK_BASIC_INFO),
                      $0,
                      &count)
        }
    }

    if kerr == KERN_SUCCESS {
        print("Memory in use (in bytes): \(info.resident_size)")
    }
    else {
        print("Error with task_info(): " +
            (String(cString: mach_error_string(kerr), encoding: String.Encoding.ascii) ?? "unknown error"))
    }
}

字符串
希望对你有帮助。

dojqjjoe

dojqjjoe2#

要在Swift 5中快速复制和粘贴解决方案,请使用

func reportMemory() {
    var taskInfo = task_vm_info_data_t()
    var count = mach_msg_type_number_t(MemoryLayout<task_vm_info>.size) / 4
    let result: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
        $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
            task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
        }
    }
    let usedMb = Float(taskInfo.phys_footprint) / 1048576.0
    let totalMb = Float(ProcessInfo.processInfo.physicalMemory) / 1048576.0
    result != KERN_SUCCESS ? print("Memory used: ? of \(totalMb)") : print("Memory used: \(usedMb) of \(totalMb)")
}

字符串

r7knjye2

r7knjye23#

当与C函数交互时,你不能依赖编译器的错误消息--一个参数一个参数地分解它,点击命令直到你知道你在处理什么。首先,你遇到的类型是:

  • task_name_tUInt32
  • task_flavor_tUInt32
  • task_info_tUnsafeMutablePointer<Int32>
  • UnsafeMutablePointer<mach_msg_type_number_t>UnsafeMutablePointer<UInt32>
  • kern_return_t -Int32

这里有一个棘手的Swift位沿着,代码中有一个bug。首先,task_info_out参数需要是UnsafeMutablePointer<UInt32>,但实际上需要指向mach_task_basic_info的示例。我们可以通过创建一个UnsafeMutablePointer<mach_task_basic_info>并在调用时将其 Package 在 * 另一个 * UnsafeMutablePointer中来解决这个问题-编译器将使用类型推断来知道我们希望 Package 指针被子类型化为UInt32
第二,在应该调用sizeinfo(mach_task_basic_info)的时候调用了sizeof(mach_task_basic_info_t)(指向mach_task_basic_info的指针),所以字节数太少,无法容纳数据结构。
在进一步的研究中,这变得有点复杂。最初的代码是不正确的,因为size应该被初始化为常量MACH_TASK_BASIC_INFO_COUNT。不幸的是,这是一个宏,而不是一个简单的常量:

#define MACH_TASK_BASIC_INFO_COUNT (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))

字符串
Swift没有导入这些,所以我们需要自己重新定义它。下面是所有这些的工作代码:

// constant
let MACH_TASK_BASIC_INFO_COUNT = (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))

// prepare parameters
let name   = mach_task_self_
let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
var size   = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)

// allocate pointer to mach_task_basic_info
var infoPointer = UnsafeMutablePointer<mach_task_basic_info>.alloc(1)

// call task_info - note extra UnsafeMutablePointer(...) call
let kerr = task_info(name, flavor, UnsafeMutablePointer(infoPointer), &size)

// get mach_task_basic_info struct out of pointer
let info = infoPointer.move()

// deallocate pointer
infoPointer.dealloc(1)

// check return value for success / failure
if kerr == KERN_SUCCESS {
    println("Memory in use (in bytes): \(info.resident_size)")
} else {
    let errorString = String(CString: mach_error_string(kerr), encoding: NSASCIIStringEncoding)
    println(errorString ?? "Error: couldn't parse error string")
}

nr9pn0ug

nr9pn0ug4#

内特的回答很好,但你可以做一个调整来简化它。
首先,不是分配/释放task_basic_info指针,而是在堆栈上创建结构体,然后使用withUnsafeMutablePointer直接获取指向它的指针,然后传入。

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"))
    }
}

字符串

ia2d9nvy

ia2d9nvy5#

Swift 5 +合并,连续内存监控
像XCODE一样以MB为单位显示确切的内存

import Foundation
import Combine

 enum MemoryMonitorState {
    case started
    case paused
}

class MemoryUsageCustom {
    
    private var displayLink: CADisplayLink!

    var state = MemoryMonitorState.paused
    
    let subject = PassthroughSubject<String, Never>()

    
    private static var sharedInstance: MemoryUsageCustom!
    
    public class func shared() -> MemoryUsageCustom {
        if self.sharedInstance == nil {
            self.sharedInstance = MemoryUsageCustom()
        }
        return self.sharedInstance
    }
    
    private init() {
        self.configureDisplayLink()

    }
    
    func startMemoryMonitor() {
        
        if self.state == .started {
            return
        }
        
        self.state = .started
        self.start()
    }
    
    func stopMemoryMonitor() {
        self.state = .paused
        self.pause()
    }
    

    //--------------------------------------------------------------------------------
    
    //MARK:- Display Link
    
    //--------------------------------------------------------------------------------

 
    func configureDisplayLink() {
        self.displayLink = CADisplayLink(target: self, selector: #selector(displayLinkAction(displayLink:)))
        self.displayLink.isPaused = true
        self.displayLink?.add(to: .current, forMode: .common)
    }
    
    private func start() {
        self.displayLink?.isPaused = false
    }
    
    /// Pauses performance monitoring.
    private func pause() {
        self.displayLink?.isPaused = true
    }
    
    @objc func displayLinkAction(displayLink: CADisplayLink) {
        let memoryUsage = self.memoryUsage()
        
        let bytesInMegabyte = 1024.0 * 1024.0
        let usedMemory = Double(memoryUsage.used) / bytesInMegabyte
        let totalMemory = Double(memoryUsage.total) / bytesInMegabyte
        let memory = String(format: "%.1f of %.0f MB used", usedMemory, totalMemory)

     //   self.memoryString = memory
        subject.send(memory)
    }
    
    func memoryUsage() -> (used: UInt64, total: UInt64) {
        var taskInfo = task_vm_info_data_t()
        var count = mach_msg_type_number_t(MemoryLayout<task_vm_info>.size) / 4
        let result: kern_return_t = withUnsafeMutablePointer(to: &taskInfo) {
            $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
                task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
            }
        }
        
        var used: UInt64 = 0
        if result == KERN_SUCCESS {
            used = UInt64(taskInfo.phys_footprint)
        }
        
        let total = ProcessInfo.processInfo.physicalMemory
        return (used, total)
    }

}

字符串
如何使用

//Start Monitoring 
    MemoryUsageCustom.shared().startMemoryMonitor()

var storage = Set<AnyCancellable>()

    MemoryUsageCustom.shared().subject.sink {[weak self] (string) in
        print(string)

    }.store(in: &storage)

ujv3wf0j

ujv3wf0j6#

Airspeed Velocity在Swift 3中的回答

func GetMemory()
{
    var info = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout.size(ofValue: info))/4

    let kerr: kern_return_t = withUnsafeMutablePointer(to: &info)
    {

        task_info(mach_task_self_,
                  task_flavor_t(MACH_TASK_BASIC_INFO),
                  $0.withMemoryRebound(to: Int32.self, capacity: 1) { zeroPtr in
                    task_info_t(zeroPtr)
                  },
                  &count)

    }

    if kerr == KERN_SUCCESS {
        print("Memory in use (in bytes): \(info.resident_size)")
    }
    else {
        print("Error with task_info(): " +
            (String.init(validatingUTF8: mach_error_string(kerr)) ?? "unknown error"))
    }
}

字符串

ohfgkhjo

ohfgkhjo7#

对于Linux:

import Foundation

@available(macOS 10.13, *)
public func shell(_ args: String...) throws -> String? {
    let task = Process()
    task.launchPath = "/usr/bin/env"
    task.arguments = args
    
    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    
    try task.run()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    if let output = String(data: data, encoding: String.Encoding.utf8) {
        if output.count > 0 {
            //remove newline character.
            let lastIndex = output.index(before: output.endIndex)
            return String(output[output.startIndex ..< lastIndex])
        }
        task.waitUntilExit()
        return output
    } else {
        return nil
    }
}

@available(macOS 10.13, *)
public func shellWithPipes(_ args: String...) throws -> String? {
    var task: Process!
    var prevPipe: Pipe? = nil
    guard args.count > 0 else {
        return nil
    }
    for i in 0..<args.count {
        task = Process()
        task.launchPath = "/usr/bin/env"
        let taskArgs = args[i].components(separatedBy: " ")
        var refinedArgs = [String]()
        var refinedArg = ""
        for arg in taskArgs {
            if !refinedArg.isEmpty {
                refinedArg += " " + arg
                if arg.suffix(1) == "'" {
                    refinedArgs.append(refinedArg.replacingOccurrences(of: "\'", with: ""))
                    refinedArg = ""
                }
            } else {
                if arg.prefix(1) == "'" {
                    refinedArg = arg
                } else {
                    refinedArgs.append(arg)
                }
            }
        }
        task.arguments = refinedArgs
        
        let pipe = Pipe()
        if let prevPipe = prevPipe {
            task.standardInput = prevPipe
        }
        task.standardOutput = pipe
        task.standardError = pipe
        try task.run()
        prevPipe = pipe
    }
    if let data = prevPipe?.fileHandleForReading.readDataToEndOfFile(),
       let output = String(data: data, encoding: String.Encoding.utf8) {
        if output.count > 0 {
            //remove newline character.
            let lastIndex = output.index(before: output.endIndex)
            return String(output[output.startIndex ..< lastIndex])
        }
        task.waitUntilExit()
        return output
    }
    return nil
}

#if os(Linux)
public func reportMemory() {
    do {
        if let usage = try shellWithPipes("free -m", "grep Mem", "awk '{print $3 \"MB of \" $2 \"MB\"}'") {
            NSLog("Memory used: \(usage)")
        }
    } catch {
        NSLog("reportMemory error: \(error)")
    }
}

public func availableMemory() -> Int {
    do {
        if let avaiable = try shellWithPipes("free -m", "grep Mem", "awk '{print $7}'") {
            return Int(avaiable) ?? -1
        }
    } catch {
        NSLog("availableMemory error: \(error)")
    }
    return -1
}

public func freeMemory() -> Int {
    do {
        if let result = try shellWithPipes("free -m", "grep Mem", "awk '{print $4}'") {
            return Int(result) ?? -1
        }
    } catch {
        NSLog("freeMemory error: \(error)")
    }
    return -1
}
#endif

字符串

mwkjh3gx

mwkjh3gx8#

  • 斯威夫特5号酒店,纽约**

有一种通用的方法来处理task_info,它以方便的方式覆盖了所有与机器无关的任务信息结构:

struct TaskInfo {
  
  private static func taskInfo<T>(_ info: T, _ flavor: Int32) -> T {
    var info = info
    var count = mach_msg_type_number_t(MemoryLayout<T>.size / MemoryLayout<natural_t>.size)
    _ = withUnsafeMutablePointer(to: &info) {
      $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
        task_info(mach_task_self_, task_flavor_t(flavor), $0, &count)
      }
    }
    return info
  }
  
  static var basic: task_basic_info { taskInfo(task_basic_info(), TASK_BASIC_INFO) }
  static var events: task_events_info { taskInfo(task_events_info(), TASK_EVENTS_INFO) }
  static var thread_times: task_thread_times_info { taskInfo(task_thread_times_info(), TASK_THREAD_TIMES_INFO) }
  static var absolutetime: task_absolutetime_info { taskInfo(task_absolutetime_info(), TASK_ABSOLUTETIME_INFO) }
  static var kernelmemory: task_kernelmemory_info { taskInfo(task_kernelmemory_info(), TASK_KERNELMEMORY_INFO) }
  static var affinity_tag: task_affinity_tag_info { taskInfo(task_affinity_tag_info(), TASK_AFFINITY_TAG_INFO) }
  static var dyld: task_dyld_info { taskInfo(task_dyld_info(), TASK_DYLD_INFO) }
  static var extmod: task_extmod_info { taskInfo(task_extmod_info(), TASK_EXTMOD_INFO) }
  static var power: task_power_info_v2 { taskInfo(task_power_info_v2(), TASK_POWER_INFO_V2) }
  static var vm: task_vm_info { taskInfo(task_vm_info(), TASK_VM_INFO) }
  static var trace_memory: task_trace_memory_info { taskInfo(task_trace_memory_info(), TASK_TRACE_MEMORY_INFO) }
  static var wait_state: task_wait_state_info { taskInfo(task_wait_state_info(), TASK_WAIT_STATE_INFO) }
  static var flags: task_flags_info { taskInfo(task_flags_info(), TASK_FLAGS_INFO) }
}

字符串
用途:

let basic = TaskInfo.basic
print("Memory usage: \(basic.resident_size / (1024 * 1024)) MB")

let vm = TaskInfo.vm
print("VM memory usage: \(vm.internal / (1024 * 1024)) MB")

let power = TaskInfo.power
print("Energy usage: \(power.task_energy) nJ (nano Joules)")

/*
Prints:

Memory usage: 34 MB
VM memory usage: 9 MB
Energy usage: 204697898 nJ (nano Joules)
*/

相关问题