Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa memory management when using initWithBitmapDataPlanes to create NSImage

I am creating an NSImage from an unsigned char * of 24bit RGB data like so:

NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
                            initWithBitmapDataPlanes:(unsigned char **)&data
                            pixelsWide:gWidth
                            pixelsHigh:gHeight
                            bitsPerSample:8
                            samplesPerPixel:3
                            hasAlpha:NO
                            isPlanar:NO
                            colorSpaceName:NSCalibratedRGBColorSpace
                            bytesPerRow:gWidth*3
                            bitsPerPixel:24];

NSImage *img = [[NSImage alloc] initWithSize:NSMakeSize(gWidth, gHeight)];
[img addRepresentation:bitmap];

The problem I'm having is that I am later writing more stuff to 'data' and I know that NSImage is not making a copy of it. I say that because if I later write all 0s to my data buffer then the image goes all black.

I'm struggling with Objective C so bear with me if this is trivial.

If I make a local copy of 'data' and never free it then things work well, but obviously leaks:

unsigned char *copy_of_data = new unsigned char[len];
memcpy(copy_of_data, data, len);

How can I either:

(1) make the initWithBitmapDataPlanes create its own copy and handle deallocation?

or (2) free the data myself when appropriate after the image no longer needs it?

like image 707
spartygw Avatar asked Apr 18 '13 23:04

spartygw


1 Answers

It might be simplest to pass NULL for the planes parameter. Then, after the image rep has been allocated and initialized, ask it for its -bitmapData and copy your data into that. This approach is suggested in the docs:

If planes is NULL or an array of NULL pointers, this method allocates enough memory to hold the image described by the other arguments. You can then obtain pointers to this memory (with the getPixel:atX:y: or bitmapData method) and fill in the image data. In this case, the allocated memory will belong to the object and will be freed when it’s freed.

Emphasis added.

like image 149
Ken Thomases Avatar answered Sep 19 '22 08:09

Ken Thomases