Ben Lu
Ben Lu

Reputation: 3042

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

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!

Upvotes: 9

Views: 4624

Answers (2)

Ahmed
Ahmed

Reputation: 945

Have you tried the following?

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

Ref: Using Legacy C APIs with Swift

Upvotes: 1

matt
matt

Reputation: 534925

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

imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength)

Upvotes: 20

Related Questions