【发布时间】:2017-07-03 21:11:50
【问题描述】:
如何在 Swift 中使用 UnsafeMutablePointer<OpaquePointer> 和一些 Core Foundation 框架?为什么要有UnsafeMutablePointer<OpaquePointer>?
给定,一般:一些UnsafeMutablePointer<SomeType> 其中typealias SomeType = OpaquePointer
特定示例 API
// SOURCE: import ApplicationServices.PrintCore
typealias PMPrinter = OpaquePointer
func PMSessionGetCurrentPrinter(_ printSession: PMPrintSession, _ currentPrinter: UnsafeMutablePointer<PMPrinter>)
func PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)
特定用例示例:获取打印机支持的纸张列表
let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, ¤tPrinterOptional!)
guard let currentPrinter = currentPrinterOptional else { return }
// Get the array of pre-defined PMPapers this printer supports.
// PMPrinterGetPaperList(PMPrinter, UnsafeMutablePointer<Unmanaged<CFArray>?>)
var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() as [AnyObject]? else { return }
观察到的错误
编译的东西不会运行。看起来(也许)合理的语法无法编译。
上面的示例得到以下(预期的)运行时“致命错误:在展开可选值时意外发现 nil”。
一些选择其他尝试:
// Compile Error: Address of variable 'currentPrinter' taken before is is initialized
var currentPrinter: PMPrinter
PMSessionGetCurrentPrinter(printSession, ¤tPrinter)
// Compile Error: Nil cannot initialze specified type 'PMPrinter' (aka 'OpaquePointer')
var currentPrinter: PMPrinter = nil
PMSessionGetCurrentPrinter(printSession, ¤tPrinter)
// Compile Error: Variable 'currentPrinterPtr' used before being initialized
var currentPrinterPtr: UnsafeMutablePointer<PMPrinter>
PMSessionGetCurrentPrinter(printSession, currentPrinterPtr)
// Compile OK: actually compiles
// Runtime Error: unexpectedly found nil while unwrapping an Optional value
var currentPrinterOptional: PMPrinter? = nil
PMSessionGetCurrentPrinter(printSession, ¤tPrinterOptional!)
资源
Apple: Core Printing ⇗
Apple: Using Swift with Cocoa and Objective-C ⇗
虽然文档提供了有用的信息,但类型别名为 UnsafeMutablePointer<OpaquePointer> 的 UnsafeMutablePointer<PMPrinter> 的可行实现一直难以捉摸。
【问题讨论】: