iosobjective-ccswiftcgpdf

How do I setup a CGPDFOperatorTableSetCallback in SWIFT (not Objective C)


I am trying to parse PDF files and I've nearly got the code working. The only thing I can't seem to figure out is to translate the following Objective C code, into Swift. I need to call my own written function to register it as a callback.

The Objective-C code is:

CGPDFOperatorTableSetCallback(operatorTable, "q", &op_q);

and the function is

static void op_q(CGPDFScannerRef s, void *info) {
    // Do whatever you have to do in here
    // info is whatever you passed to CGPDFScannerCreate
}

What would the Swift equivalents be?


Solution

  • You don't need to create your own op_q function to use as a function pointer if you don't want to. Use Swift's closure syntax:

    CGPDFOperatorTableSetCallback(operatorTable, ("q" as NSString).UTF8String) { (s, info) -> Void in
        // ...
    }
    

    Here ("q" as NSString).UTF8String gives you an UsafePointer<Int8> which acts as a const char * bridged to Swift from C.

    If you wanted to use a function pointer, it might look like this:

    func op_q(s: CGPDFScannerRef, _ info: UnsafeMutablePointer<Void>) {
        // ...
    }