chebur
chebur

Reputation: 634

Convert CFContextRef to mutable void pointer in swift?

I'm trying to convert this objc code to swift:

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

So far I ended up with this:

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)

The problem is that CGBitmapContextCreate returns CGContext type and NSGraphicsContext initializer accepts graphicsPort as CMutableVoidPointer type. So how can I convert CGContext to CMutableVoidPointer?

related reverse type casting found here, but it didn't provide much help to me How to convert COpaquePointer in swift to some type (CGContext? in particular)

Upvotes: 5

Views: 1747

Answers (2)

chebur
chebur

Reputation: 634

I ended up with the reinterpretCast function returning intermediate Int variable for the bitmapContext address.

var bitmapContext: CGContext = CGBitmapContextCreate(...)

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

Upvotes: 2

Jack
Jack

Reputation: 16855

The documentation here:https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html

states the following:

When a function is declared as taking a CMutableVoidPointer argument, it can accept the same operands as CMutablePointer for any type Type.

From that, it should work like this:

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

Extended practically, you should be able to pass in &bitmapContext directly to a CMutableVoidPointer argument.

Swift doesn't have "pointers" in the C sense.

Upvotes: 0

Related Questions