Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecast UnsafeMutablePointer<Void> to UnsafeMutablePointer<#Struct type#>

Tags:

swift

I created a struct in Swift called RGB, simple enough:

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
    }
}

And I have a pointer var imageData: UnsafeMutablePointer<PixelRGB>!.

I wish to malloc some space for this pointer, but malloc returns UnsafeMutablePointer<Void> and I cannot cast it like below:

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

Anyway to solve this? Thank you for your help!

like image 306
Ben Lu Avatar asked Sep 24 '14 00:09

Ben Lu


2 Answers

I think what you want to say is something like this:

imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength)
like image 88
matt Avatar answered Oct 31 '22 15:10

matt


Have you tried the following?

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

Ref: Using Legacy C APIs with Swift

like image 38
Ahmed Avatar answered Oct 31 '22 16:10

Ahmed