9

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!

4
  • 2
    How about imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength)? Commented Sep 24, 2014 at 0:37
  • @matt This should be an answer. Commented Sep 24, 2014 at 0:59
  • Okey-dokey, will do. Commented Sep 24, 2014 at 1:01
  • You would only malloc it if it needs to have a dynamic lifetime. Otherwise, why don't you just have a variable of type PixelRGB? Commented Sep 24, 2014 at 19:01

2 Answers 2

20

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

imageData = UnsafeMutablePointer<PixelRGB>.alloc(dataLength) 
Sign up to request clarification or add additional context in comments.

4 Comments

@AntonHolmquist imageData.destroy()
@AntonHolmquist The opposite of alloc() is dealloc(). The destroy() method is the counterpart of initialize().
This answer is a better way to solve the OPs problem, but it does not answer the question asked in the title. Either the title should change, or someone should answer the question about type casting.
@Fooberman I'm not sure what you're after here, but feel free to supply your own answer to the original question.
1

Have you tried the following?

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

Ref: Using Legacy C APIs with Swift

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.