Typecast UnsafeMutablePointer <void>到UnsafeMutablePointer&lt; #Struct type#&gt; </void>

时间:2014-09-24 00:32:17

标签: swift

我在Swift中创建了一个名为RGB的结构,很简单:

struct PixelRGB {
    var r: CUnsignedChar = 0
    var g: CUnsignedChar = 0
    var b: CUnsignedChar = 0

    init(red: CUnsignedChar, green: CUnsignedChar, blue: CUnsignedChar) {
        r = red
        g = green
        b = blue
    }
}

我有一个指针var imageData: UnsafeMutablePointer<PixelRGB>!

我希望为此指针malloc一些空间,但malloc返回UnsafeMutablePointer<Void>,我不能像下面那样强制转换它:

imageData = malloc(UInt(dataLength)) as UnsafeMutablePointer<PixelRGB> // 'Void' is not identical to `PixelRGB`

无论如何要解决这个问题?谢谢你的帮助!

2 个答案:

答案 0 :(得分:19)

我想你想说的是这样的:

imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength)

答案 1 :(得分:1)

您是否尝试过以下操作?

imageData = unsafeBitCast(malloc(UInt(dataLength)), UnsafeMutablePointer<PixelRGB>.self)

参考:Using Legacy C APIs with Swift