我在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`
无论如何要解决这个问题?谢谢你的帮助!
答案 0 :(得分:19)
我想你想说的是这样的:
imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength)
答案 1 :(得分:1)
您是否尝试过以下操作?
imageData = unsafeBitCast(malloc(UInt(dataLength)), UnsafeMutablePointer<PixelRGB>.self)