将 'UnsafeMutableRawPointer' 类型的变量转换为 Swift 中的 UnsafeMutablePointer<> 3
Casting a variable of type 'UnsafeMutableRawPointer' to UnsafeMutablePointer<> in Swift 3
从 class 定义开始,如下所示:
class Player {
var playbackFile: AudioFileID? = nil
var packetPosition: Int64 = 0
var numPacketsToRead: UInt32 = 0
var packetDescs: UnsafeMutablePointer<AudioStreamPacketDescription>? = nil
var isDone = false
}
然后定义一个回调函数:
let AQOutputCallback: AudioQueueOutputCallback = {(inUserData, inAQ, inCompleteAQBuffer) -> () in
let aqp = UnsafeMutablePointer<Player>(inUserData).pointee // this gives an error
// more code
}
这会导致第二行出现错误:“无法使用 'UnsafeMutableRawPointer?'
类型的参数列表调用类型 'UnsafeMutablePointer' 的初始值设定项
如何在 Swift 3 中从类型 'UnsafeMutableRawPointer?' 正确转换为 'UnsafeMutablePointer'?
以下修改消除了错误:
let aqp = inUserData!.assumingMemoryBound(to: Player.self).pointee
要将 MutableRawPointer 转换为对象,我们使用 fromOpaque api
/// Unsafely turns an opaque C pointer into an unmanaged class reference.
///
/// This operation does not change reference counts.
///
/// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
///
/// - Parameter value: An opaque C pointer.
/// - Returns: An unmanaged class reference to `value`.
public static func fromOpaque(_ value: UnsafeRawPointer) -> Unmanaged<Instance>
示例:
var info:UnsafeMutableRawPointer = ....
let obj = Unmanaged<$AnyObject>.fromOpaque(info).takeUnretainedValue()
从 class 定义开始,如下所示:
class Player {
var playbackFile: AudioFileID? = nil
var packetPosition: Int64 = 0
var numPacketsToRead: UInt32 = 0
var packetDescs: UnsafeMutablePointer<AudioStreamPacketDescription>? = nil
var isDone = false
}
然后定义一个回调函数:
let AQOutputCallback: AudioQueueOutputCallback = {(inUserData, inAQ, inCompleteAQBuffer) -> () in
let aqp = UnsafeMutablePointer<Player>(inUserData).pointee // this gives an error
// more code
}
这会导致第二行出现错误:“无法使用 'UnsafeMutableRawPointer?'
类型的参数列表调用类型 'UnsafeMutablePointer' 的初始值设定项如何在 Swift 3 中从类型 'UnsafeMutableRawPointer?' 正确转换为 'UnsafeMutablePointer'?
以下修改消除了错误:
let aqp = inUserData!.assumingMemoryBound(to: Player.self).pointee
要将 MutableRawPointer 转换为对象,我们使用 fromOpaque api
/// Unsafely turns an opaque C pointer into an unmanaged class reference.
///
/// This operation does not change reference counts.
///
/// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
///
/// - Parameter value: An opaque C pointer.
/// - Returns: An unmanaged class reference to `value`.
public static func fromOpaque(_ value: UnsafeRawPointer) -> Unmanaged<Instance>
示例:
var info:UnsafeMutableRawPointer = ....
let obj = Unmanaged<$AnyObject>.fromOpaque(info).takeUnretainedValue()