1

How to create UnsafePointer? Trying let mediaBoxPtr = UnsafePointer(mediaBox) but fails

func PDFImageData(filter: QuartzFilter?) -> NSData? {
    let pdfData = NSMutableData()
    let consumer = CGDataConsumerCreateWithCFData(pdfData);
    var mediaBox =  CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
    let mediaBoxPtr : UnsafePointer<CGRect> = nil //???? I need CGRect(x:0, y:0, bounds.size.width, bounds.size.height)
    if let pdfContext = CGPDFContextCreate(consumer, mediaBoxPtr, nil) {
      filter?.applyToContext(pdfContext)}
Marek H
  • 5,173
  • 3
  • 31
  • 42

1 Answers1

5

You don't have to create a pointer. Simply pass the address of the mediaBox variable as "inout argument" with &:

var mediaBox =  CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
if let pdfContext = CGPDFContextCreate(consumer, &mediaBox, nil) {
    // ...
}

For more information and examples, see "Interacting with C APIs":

Mutable Pointers

When a function is declared as taking an UnsafeMutablePointer<Type> argument, it can accept any of the following:

  • ...
  • An in-out expression that contains a mutable variable, property, or subscript reference of type Type, which is passed as a pointer to the address of the mutable value.
  • ...
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks, tried this but it failed to compile, now it works as a charm (I found this answer previously). The important part is to use var instead of let. I know... – Marek H Aug 11 '16 at 13:40