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?
I believe in Swift 5, we can do so using (assuming T is UInt8
)
let unsafeMutablePointer
= unsafeMutableRawPointer.bindMemory(to: UInt8.self, capacity: capacity)
In your case, you'd better use allocate(capacity:)
method.
let grayData = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With