MatterGoal
MatterGoal

Reputation: 16430

How to create a Pixel_8 buffer in swift

I'm trying to convert objective-c code in swift, and I'm completely blocked looking for a way to get a Pixel_8 buffer (that I'd normally create using calloc in objective-c) in swift.

Here is an example in Objective-c... how does it convert to swift?

Pixel_8 *buffer = (Pixel_8 *)calloc(width*height, sizeof(Pixel_8)); 

Upvotes: 2

Views: 300

Answers (2)

Martin R
Martin R

Reputation: 539955

You can use calloc() in Swift, but you have to "bind" the raw pointer to the wanted type:

let buffer = calloc(width * height, MemoryLayout<Pixel_8>.stride).assumingMemoryBound(to: Pixel_8.self)

// Use buffer ...

free(buffer)

Alternatively:

let buffer = UnsafeMutablePointer<Pixel_8>.allocate(capacity: width * height)
buffer.initialize(to: 0, count: width * height)

// Use buffer ...

buffer.deinitialize()
buffer.deallocate(capacity: width * height)

But the most simple solution would be to allocate a Swift array:

var buffer = [Pixel_8](repeating: 0, count: width * height)

which is memory-managed automatically. You can pass buffer to any function expecting a UnsafePointer<Pixel_8>, or pass &buffer to any function expecting a UnsafeMutablePointer<Pixel_8>.

Upvotes: 2

Nazmul Hasan
Nazmul Hasan

Reputation: 10600

Trying with this way

Declaration

 typealias Pixel_8 = UInt8

swift3

var buffer: Pixel_8? = (calloc(width * height, MemoryLayout<Pixel_8>.size) as? Pixel_8)

swift2

  var buffer = (calloc(width * height, sizeof(Pixel_8)) as! Pixel_8) 

Apple API reference

Upvotes: 0

Related Questions