在Swift 3中将UnsafeMutableRawPointer转换为UnsafeMutablePointer <t>

时间:2016-09-17 13:42:54

标签: cocoa-touch swift3

我有这段代码

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

在Swift 3中没有编译。如何修复此问题?

5 个答案:

答案 0 :(得分:30)

我遇到了类似的问题,但与malloc无关。如果您的代码需要使用Swift 3处理C库,则必须处理void *,这相当于Swift 3中的UnsafeMutableRawPointer。您的代码需要将其视为特定结构。但不知何故,swift 3编译器对我来说很难进行投射。我花了一些时间来弄明白,我喜欢分享我的代码如何做到这一点。

以下代码演示了向UnsafeMutableRawPointer投射UnsafeMutablePointer<T>,修改其指针,并确保更新原始Context

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"

答案 1 :(得分:9)

在您的情况下,您最好使用allocate(capacity:)方法。

let grayData = UnsafeMutablePointer<UInt8>.allocate(capacity: width * height)

答案 2 :(得分:1)

找到它

let grayData = malloc(width * height * MemoryLayout<UInt8>.size)!.assumingMemoryBound(to: UInt8.self)

答案 3 :(得分:1)

感谢Khanh Nguyen的回答。如果需要使用calloc(),请查看:

let imageData =  calloc(width * height, MemoryLayout<UInt32>.size).assumingMemoryBound(to: UInt32.self)

我发现我需要在图形应用程序中实际使用“calloc”来获取位图。我看到的是,如果使用malloc或Swift的分配(容量:),则分配具有随机垃圾(正如人们所预期的那样)。如果这被用作获取图像位图的起点,那么如果图像的背景清晰,您将在模拟器中看到随机垃圾。真正的设备在绘制图像时显然会清除它,而模拟器将清晰的背景视为无操作。之后可以进行以下UIImage扩展来获取位图(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
    }

}

答案 4 :(得分:0)

我相信Swift 5,我们可以使用(假设T为UInt8

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