How to use UnsafeMutablePointer in Swift?

前端 未结 1 458
名媛妹妹
名媛妹妹 2021-01-13 15:43

How does one use an UnsafeMutablePointer in Swift with some Core Foundation framework? Why have an UnsafeMutablePointer

1条回答
  •  梦毁少年i
    2021-01-13 16:43

    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?
    PMPrinterGetPaperList(currentPrinter, &paperListUnmanaged)
    guard let paperList = paperListUnmanaged?.takeUnretainedValue() else {
        fatalError()
    }
    for idx in 0..

    0 讨论(0)
提交回复
热议问题