Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the swift equivalent of this cast?

I want to convert this into swift, or at least find something that does the same thing.

 size_t width = CGImageGetWidth(spriteImage);
 size_t height = CGImageGetHeight(spriteImage);

 GLubyte * spriteData = (GLubyte *) calloc(width*height*4, sizeof(GLubyte));

I need to initialize the spriteData pointer in swift of the right size.

like image 714
NJGUY Avatar asked Oct 30 '14 02:10

NJGUY


2 Answers

The first two of those are of type size_t, which maps to Uint in Swift, and the last is GLubyte, which maps to UInt8. This code will initialize spriteData as an array of GLubyte, which you could pass to any C function that needs an UnsafeMutablePointer<GLubyte> or UnsafePointer<GLubyte>:

let width = CGImageGetWidth(spriteImage)
let height = CGImageGetHeight(spriteImage)    
var spriteData: [GLubyte] = Array(count: Int(width * height * 4), repeatedValue: 0)

What do you need to do with spriteData?

like image 108
Nate Cook Avatar answered Sep 25 '22 20:09

Nate Cook


The straightforward way is:

var spriteData = UnsafeMutablePointer<GLubyte>.alloc(Int(width * height * 4))

Note that, if you did this, you have to dealloc it manually.

spriteData.dealloc(Int(width * height * 4))

/// Deallocate `num` objects.
///
/// :param: num number of objects to deallocate.  Should match exactly
/// the value that was passed to `alloc()` (partial deallocations are not
/// possible).
like image 42
rintaro Avatar answered Sep 24 '22 20:09

rintaro