Convert UnsafeMutableRawPointer to UnsafeMutablePointer <T> in swift 3
I ran into a similar problem but had nothing to do with malloc . If your code needs to deal with C libraries with Swift 3, you need to deal with void * , which is equivalent to UnsafeMutableRawPointer in Swift 3. Your code should consider it as a specific structure. But somehow, the fast compiler 3 is hard for me to cast. I took some time to figure this out and I like to share my code on how to do this.
Here is the code demonstrating casting UnsafeMutableRawPointer - UnsafeMutablePointer<T> , change its pointee and make sure the original Context updated.
struct Context { var city = "Tokyo" } var context: Context = Context() let rawPtr = UnsafeMutableRawPointer(&context) let opaquePtr = OpaquePointer(rawPtr) let contextPtr = UnsafeMutablePointer<Context>(opaquePtr) context.city // "Tokyo" contextPtr.pointee.city = "New York" context.city // "New York" Thanks to Khanh Nguyen for the answer above. If you need to use calloc (), see:
let imageData = calloc(width * height, MemoryLayout<UInt32>.size).assumingMemoryBound(to: UInt32.self) I found that I needed to use "calloc" in a graphics application to get a bitmap. I saw that if malloc or Swift allocate (capacity :) were used, then the distribution had random garbage (as you would expect). If this was used as a starting point for obtaining a bitmap image, you would see random garbage in the simulator if the background of the image were clean. The real device seems to clear it when drawing the image, and the simulator considers the transparent background as no-op. Able to then do the following UIImage extension to get a bitmap (Swift 3.0):
extension UIImage { func unSafeBitmapData() -> UnsafeMutablePointer<UInt32>? { guard let cgImage = self.cgImage else { return nil } let width = Int(self.size.width) let height = Int(self.size.height) let bitsPerComponent = 8 let bytesPerPixel = 4 let bytesPerRow = width * bytesPerPixel let maxPix = width * height let imageData = calloc(maxPix, MemoryLayout<UInt32>.size).assumingMemoryBound(to: UInt32.self) let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { return nil } imageContext.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: self.size)) return imageData } }