Convert UnsafeMutableRawPointer to UnsafeMutablePointer<T> in swift 3
I ran into a similar problem, but nothing to do with malloc
. If your code needs to deal with C libraries with Swift 3, you have to deal with void *
which is equivalent to UnsafeMutableRawPointer
in Swift 3. Your code needs to treat it as a certain structure. But somehow, swift 3 compiler is being hard on me for casting. I spent some time to figured it out, and I like to share my code how to do that.
Here is the code to demonstrate casting UnsafeMutableRawPointer
to UnsafeMutablePointer<T>
, modify its pointee, and make sure the original Context
is 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"
In your case, you'd better use allocate(capacity:)
method.
let grayData = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height)