I have a memory leak in my program where I convert a NSImage to a byte array. I tried to dispose of all variables and use an autoreleasepool:
void LoadNewScreenImage() { byte[] pixels; using (NSAutoreleasePool autoreleasepool = new NSAutoreleasePool()) using (NSImage nsimage = computerInterface.GetComputerScreenForDisplayIndex(0)) using (CGImage image = nsimage.CGImage) using (CGDataProvider dataProvider = image.DataProvider) using (NSData data = dataProvider.CopyData()) { pixels = new byte[data.Length]; System.Runtime.InteropServices.Marshal.Copy(data.Bytes, pixels, 0, Convert.ToInt32(data.Length)); } }
where computerInterface.GetComputerScreenForDisplayIndex(0)
is a native function which returns a screenshot of the computer:
-(NSImage*)getComputerScreenForDisplayIndex:(NSInteger) displayIndex
{
NSImage* computerScreenshot = 0;
CGDisplayCount displayCount=0;
if(self.displays == nil)
{
self.error = CGDisplayNoErr;
displayCount = 0;
//allocate enough memory to hold all the display ids that we have
self.displays = (CGDirectDisplayID *)calloc((size_t)displayCount, sizeof(CGDirectDisplayID));
//how many displays do we have?
self.error = CGGetActiveDisplayList(0, NULL, &displayCount);
}
//if there are displays
if(self.error != CGDisplayNoErr)
return 0;
//get the list of active displays
self.error = CGGetActiveDisplayList(displayCount, self.displays, &displayCount);
self.image = CGDisplayCreateImage(self.displays[displayIndex]);
computerScreenshot = [[NSImage alloc] initWithCGImage:self.image size:(NSSize){(CGFloat)CGImageGetWidth(self.image),(CGFloat)(CGImageGetHeight(self.image))}];
CGImageRelease(self.image);
return computerScreenshot;
}
I've tested this native function in a pure objective-c program and I don't get any memory leaks. I am calling LoadNewScreenImage()
from the main thread. Does anyone know what is causing this leak or how I could get rid of it? Any help is very much appreciated!