将“UnsafeMutableRawPointer”类型的变量强制转换为UnsafeMutablePointer<>在Swift 3中

时间:2016-11-25 23:46:20

标签: swift3 core-audio

从类定义开始,如下所示:

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'的初始值设定项?

如何从“UnsafeMutableRawPointer”类型中正确转换? Swift 3中的'UnsafeMutablePointer'?

2 个答案:

答案 0 :(得分:5)

以下修改消除了错误:

let aqp = inUserData!.assumingMemoryBound(to: Player.self).pointee

答案 1 :(得分:0)

将MutableRawPointer转换为object,我们使用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()