2

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?

JAL
  • 41,701
  • 23
  • 172
  • 300
0xT0mT0m
  • 656
  • 5
  • 15

1 Answers1

1

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>) {
    // ...
}
JAL
  • 41,701
  • 23
  • 172
  • 300
  • this is not working. – cenk ebret Apr 01 '16 at 06:57
  • @cenkebret Can you elaborate a little more on what isn't working? Is the callback not even entering the closure? Maybe ask a new question and link back here to provide context. – JAL Apr 01 '16 at 11:19
  • it is entering, but info param is always nil – cenk ebret Apr 01 '16 at 13:51
  • @cenkebret which syntax are you using? The Swift closure or the function pointer? Can you ask a new question and post your full code? – JAL Apr 01 '16 at 13:56
  • i have posted the question: http://stackoverflow.com/questions/36358521/cgpdfoperatorcallback-pdf-parser-issue-on-swift – cenk ebret Apr 01 '16 at 14:11