在Swift中将CFContextRef转换为可变的void指针?

时间:2014-06-18 12:39:47

标签: pointers types casting swift void

我正在尝试将此objc代码转换为swift:

CGContextRef contextRef = CGBitmapContextCreate(NULL,
                                                proposedRect.size.width,
                                                proposedRect.size.height,
                                                CGImageGetBitsPerComponent(imageRef),
                                                0,
                                                colorSpaceRef,
                                                (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:contextRef flipped:NO];

到目前为止,我最终得到了这个:

var bitmapContext: CGContext = CGBitmapContextCreate(data, UInt(proposedRect.width), UInt(proposedRect.height), CGImageGetBitsPerComponent(image), 0, colorSpace, CGBitmapInfo(CGImageAlphaInfo.PremultipliedFirst.toRaw()))
let context = NSGraphicsContext(graphicsPort: bitmapContext, flipped: false)

问题在于CGBitmapContextCreate返回CGContext类型,NSGraphicsContext初始化程序接受graphicsPort作为CMutableVoidPointer类型。那么如何将CGContext转换为CMutableVoidPointer

这里有相关的反向型铸造,但它对我没有太大帮助 How to convert COpaquePointer in swift to some type (CGContext? in particular)

2 个答案:

答案 0 :(得分:2)

我最终使用reinterpretCast函数返回Int地址的中间bitmapContext变量。

var bitmapContext: CGContext = CGBitmapContextCreate(...)

let bitmapContextAddress: Int = reinterpretCast(bitmapContext)
let bitmapContextPointer: CMutableVoidPointer = COpaquePointer(UnsafePointer<CGContext>(bitmapContextAddress))
let context = NSGraphicsContext(graphicsPort: bitmapContextPointer, flipped: false)

答案 1 :(得分:0)

此处的文档:https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html

陈述如下:

  

当函数声明为采用CMutableVoidPointer参数时,   对于任何类型,它都可以接受与CMutablePointer相同的操作数   类型。

从那以后,它应该像这样工作:

var p: CMutablePointer<CGContext> = &bitmapContext
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:p flipped:NO];

实际上,您应该能够将&bitmapContext直接传递给CMutableVoidPointer参数。

斯威夫特没有&#34;指针&#34;在C意义上。