How does one use an UnsafeMutablePointer
in Swift with some Core Foundation framework? Why have an UnsafeMutablePointer
PMPrinter
and PMPaper
are defined in the PrintCore framework
as pointer to an "incomplete type"
typedef struct OpaquePMPrinter* PMPrinter;
typedef struct OpaquePMPaper* PMPaper;
Those are imported into Swift as OpaquePointer
, and are a bit
cumbersome to use.
The second argument to PMSessionGetCurrentPrinter()
is a pointer to
a non-optional PMPrinter
variable, and in Swift it must be
initialized before being passed as an inout argument. One possible way
to initialize a null-pointer is to use unsafeBitCast
.
The easiest way to get the PMPaper
objects from the array seems to
be to use CFArrayGetValueAtIndex()
instead of bridging it to a
Swift array. That returns a UnsafeRawPointer
which can be converted
to an OpaquePointer
.
This worked in my test:
let printInfo = NSPrintInfo.shared()
let printSession = PMPrintSession(printInfo.pmPrintSession())
var currentPrinter = unsafeBitCast(0, to: PMPrinter.self)
PMSessionGetCurrentPrinter(printSession, ¤tPrinter);
var paperListUnmanaged: Unmanaged<CFArray>?
PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
guard let paperList = paperListUnmanaged?.takeUnretainedValue() else {
fatalError()
}
for idx in 0..<CFArrayGetCount(paperList) {
let paper = PMPaper(CFArrayGetValueAtIndex(paperList, idx))!
var width = 0.0, height = 0.0
PMPaperGetWidth(paper, &width)
PMPaperGetHeight(paper, &height)
print(width, height)
}