如何从现有的 CGRect 创建 UnsafePointer<CGRect>

How to create UnsafePointer<CGRect> from existing CGRect

如何创建UnsafePointer? 尝试让 mediaBoxPtr = UnsafePointer(mediaBox) 但失败

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)}

您不必创建指针。只需传递 mediaBox 的地址 变量为 "inout argument" 和 &:

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

有关更多信息和示例,请参阅 "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.
  • ...