1

I am converting an Objective-C class that uses calloc() to create a buffer to Swift 3. Here is the pertinent part of the code I'm having issue with. In particular, the rawData assignment and usage.

CGImageRef imageRef = [capturedImage CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);

unsigned char *rawData = (unsigned char *)calloc(height * width * 4, sizeof(unsigned char));

NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
    bitsPerComponent, bytesPerRow, colorSpace,
    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;

CGFloat red = (CGFloat)rawData[byteIndex];
CGFloat green = (CGFloat)rawData[byteIndex + 1];
CGFloat blue = (CGFloat)rawData[byteIndex + 2];
jscs
  • 63,694
  • 13
  • 151
  • 195
David Nedrow
  • 1,098
  • 1
  • 9
  • 26

1 Answers1

0

From the CGBitmapContextCreate documentation:

data : UnsafeMutableRawPointer?

A pointer to the destination in memory where the drawing is to be rendered. The size of this memory block should be at least (bytesPerRow*height) bytes.

Pass NULL if you want this function to allocate memory for the bitmap. This frees you from managing your own memory, which reduces memory leak issues.

While you could figure out how to allocate the required memory block and obtain an UnsafeMutableRawPointer to it unless you have a good reason to allocate your own buffer just follow the documentation and pass NULL - no need to use calloc() at all.

HTH

Community
  • 1
  • 1
CRD
  • 52,522
  • 5
  • 70
  • 86