当前位置 : 主页 > 手机开发 > 其它 >

在Swift 3中使用withMemoryRebound的问题

来源:互联网 收集:自由互联 发布时间:2021-06-11
我有一个以前使用UnsafeMutablePointer来调用C函数的应用程序,如下所示: var size = HOST_BASIC_INFO_COUNT let hostInfo = host_basic_info_t.allocate(capacity: 1) let result = host_info(machHost, HOST_BASIC_INFO, UnsafeMuta
我有一个以前使用UnsafeMutablePointer来调用C函数的应用程序,如下所示:

var size     = HOST_BASIC_INFO_COUNT
    let hostInfo = host_basic_info_t.allocate(capacity: 1)
    let result = host_info(machHost, HOST_BASIC_INFO,
                                     UnsafeMutablePointer(hostInfo), &size)

自从迁移到Swift 3,Xcode Beta 6后,系统会提示您使用withMemoryRebound.问题是我不明白如何在这种情况下使用它,并且还没有它的文档或示例代码.
我的方法:

var size     = HOST_BASIC_INFO_COUNT
    let hostInfo = host_basic_info_t.allocate(capacity: 1)
    let temp = hostInfo.withMemoryRebound(to: host_info_t!.self, capacity: Int(size)) {
        UnsafeBufferPointer(start: $0, count: Int(size))
    }
    let result = host_statistics(machHost,
                                 HOST_BASIC_INFO,
                                 temp.baseAddress?.pointee,
                                 &size)

只是与Bad Access崩溃.使用withMemoryRebound的正确方法是什么?

hostInfo是一个UnsafeMutablePointer< host_basic_info>,以及该指针
必须“反弹”到指向HOST_BASIC_INFO_COUNT项的指针
of integer_t,正如hostInfo()函数所期望的那样:

let HOST_BASIC_INFO_COUNT = MemoryLayout<host_basic_info>.stride/MemoryLayout<integer_t>.stride
var size = mach_msg_type_number_t(HOST_BASIC_INFO_COUNT)
let hostInfo = host_basic_info_t.allocate(capacity: 1)
let result = hostInfo.withMemoryRebound(to: integer_t.self, capacity: HOST_BASIC_INFO_COUNT) {
    host_info(mach_host_self(), HOST_BASIC_INFO, $0, &size)
}

print(result, hostInfo.pointee)
hostInfo.deallocate(capacity: 1)

而不是分配/解除分配,你也可以使用
局部变量并传递其地址:

let HOST_BASIC_INFO_COUNT = MemoryLayout<host_basic_info>.stride/MemoryLayout<integer_t>.stride
var size = mach_msg_type_number_t(HOST_BASIC_INFO_COUNT)
var hostInfo = host_basic_info()

let result = withUnsafeMutablePointer(to: &hostInfo) {
    $0.withMemoryRebound(to: integer_t.self, capacity: Int(size)) {
        host_info(mach_host_self(), Int32(HOST_BASIC_INFO), $0, &size)
    }
}
print(result, hostInfo)
网友评论