首页 > 解决方案 > Convert from UnsafeMutableRawPointer to UnsafeMutablePointer, which approach is correct?

问题描述

To convert from UnsafeMutableRawPointer to UnsafeMutablePointer, both the approach works. (I'm using Swift 5.2)

// Approach 1
let unsafeMutablePointer = UnsafeBufferPointer(
    start: unsafeMutableRawPointer.assumingMemoryBound(to: UInt8.self), count: Int(size.width * size.height * 4))


// Appraoch 2
let unsafeMutablePointer = unsafeMutableRawPointer
    .bindMemory(to: UInt8.self, capacity: Int(size.width * size.height * 4))

Are they the same? Or they are meant for different purpose? (when to use which?)

I also notice for Approach 2, even if I give the wrong capacity (e.g. 0), it still works. Is it automatically assign the minimum needed capacity from the unsafeMutableRawPointer?

let unsafeMutablePointer = unsafeMutableRawPointer
    .bindMemory(to: UInt8.self, capacity: 0)

标签: iosswift

解决方案


推荐阅读