在Swift 3中使用withMemoryRebound的问题

时间:2016-08-17 11:02:53

标签: swift cocoa pointers

我有一个以前使用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的正确方法是什么?

3 个答案:

答案 0 :(得分:5)

hostInfoUnsafeMutablePointer<host_basic_info>和指针 必须“反弹”到指向HOST_BASIC_INFO_COUNT项目的指针 如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)

您也可以使用allocate/deallocate代替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) 本地变量并传递其地址:

public void showSeriesInfo() {

    try { 

        BorderPane tvShows = (BorderPane) FXMLLoader.load(getClass().getResource("/seriesapp/javafx/tvShowAbout.fxml"));

        setCenterPane(tvShows);

    } catch (Exception e) { 
        e.printStackTrace(); 
    }  
}

答案 1 :(得分:0)

withMemoryRebound与withUnsafePointer函数非常相似。

容量需要是host_info_t的大小。

您需要执行以下操作:

let temp = hostInfo.withMemoryRebound(to: host_info_t.self or type(of: host_info), capacity: MemoryLayout<host_info_t>.stride * Int(size))

另外,您不需要UnsafeBufferPointer。

答案 2 :(得分:0)

这个应该更好用swift 3

result = withUnsafePointer(to: &size) {
            $0.withMemoryRebound(to: integer_t.self, capacity: HOST_BASIC_INFO_COUNT) {
                host_info(machHost, HOST_BASIC_INFO,
                          $0,
                          &size)
            }
相关问题