Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UnsafeMutableRawPointer to UnsafeMutablePointer<T> in swift 3

I have this code

let grayData = UnsafeMutablePointer<UInt8>(other: malloc(width * height * sizeof(UInt8)))

Which doesn't compile in Swift 3. How do I fix this?

like image 277
Khanh Nguyen Avatar asked Sep 17 '16 13:09

Khanh Nguyen


3 Answers

I believe in Swift 5, we can do so using (assuming T is UInt8)

let unsafeMutablePointer
    = unsafeMutableRawPointer.bindMemory(to: UInt8.self, capacity: capacity)
like image 130
Elye Avatar answered Sep 23 '22 05:09

Elye


In your case, you'd better use allocate(capacity:) method.

let grayData = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height)
like image 11
OOPer Avatar answered Nov 18 '22 12:11

OOPer


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"
like image 33
Kaz Yoshikawa Avatar answered Nov 18 '22 12:11

Kaz Yoshikawa