Swift 2 – UnsafeMutablePointer到对象

前端之家收集整理的这篇文章主要介绍了Swift 2 – UnsafeMutablePointer到对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个方法如:
func someMethod(contextPtr: UnsafeMutablePointer<Void>)

如何从contextPtr获取对象?

func someMethod(contextPtr: UnsafeMutablePointer<Void>){    
    let object:MyObject = contextPtr.memory
}

得到:

‘Void’ is not convertible to ‘MyObject’

什么是秘密酱

更多详情:

我在这里实际做的是为SCNetworkReachability设置全局回调函数

func callback(reachability:SCNetworkReachability,flags: SCNetworkReachabilityFlags,info: UnsafeMutablePointer<Void>) {

    let r:Reachability = info.memory
}

然后添加回调如下:

var context = SCNetworkReachabilityContext(version: 0,info: nil,retain: nil,release: nil,copyDescription: nil)
var s = self
withUnsafeMutablePointer(&s) {
    context.info = UnsafeMutablePointer($0)
}
SCNetworkReachabilitySetCallback(reachability,callback,&context)
这应该工作:将对象指针传递为不透明的非托管指针
回调:
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(myObject).toOpaque())
SCNetworkReachabilitySetCallback(reachability,&context)

并通过以下方式在回调中检索:

func callback(reachability:SCNetworkReachability,info: UnsafeMutablePointer<Void>) {

    let myObject = Unmanaged<MyObject>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()

}

当然,这假设有一些对该对象的强烈引用存在
只要回调被安装,使对象不是
释放。

更新:请注意,从对象指针到void指针的转换
如果您愿意使用“不安全”功能,则可以简化后退:

context.info = unsafeAddressOf(myObject)
// ...
myObject = unsafeBitCast(info,MyObject.self)

生成的汇编代码 – 就我所见 – 相同。

更新2:另请参阅How to cast self to UnsafeMutablePointer<Void> type in swift了解更多信息
关于“桥接”和一些可以在这里使用的帮助函数

Swift 3更新(Xcode 8 beta 6):

var context = SCNetworkReachabilityContext(version: 0,copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())

// ...

func callback(reachability:SCNetworkReachability,info: UnsafeMutableRawPointer?) {
    if let info = info {
        let myObject = Unmanaged<MyObject>.fromOpaque(info).takeUnretainedValue()
        // ...
    }
}

猜你在找的Swift相关文章