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?