使用autoreleasepool时NSImage转换中的内存泄漏

时间:2016-09-01 13:11:35

标签: macos xamarin memory-leaks xamarin.mac

我的程序中存在内存泄漏,我将NSImage转换为字节数组。我试图处理所有变量并使用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));
        }
    }

其中computerInterface.GetComputerScreenForDisplayIndex(0)是一个本机函数,它返回计算机的屏幕截图:

-(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;
}

我在一个纯粹的Objective-c程序中测试了这个原生函数,但我没有得到任何内存泄漏。有谁知道造成这种泄漏的原因或我怎么能摆脱它?非常感谢任何帮助!

0 个答案:

没有答案
相关问题