Python Memory leak when accessing GetCurrentImage() from DirectShow comtype
Question: I have to debug someone elses code that has a memory leak. It uses up all the
RAM and then eventually crashes (at a rate of 4Mb/s). I isolated it down to a
call that grabs a screen shot of a video filter and saves it to a object named
**lbDib**. But then Python does not free it afterward it is used. I have tried
to Del it, then call gc.collect(). I have assigned it to zero or None etc. But
the memory is not freed.

After some googling I came across this:

<http://msdn.microsoft.com/en-
us/library/windows/desktop/dd390556%28v=vs.85%29.aspx>

Which states:

> The VMR allocates the memory for the image and returns a pointer to it in
> the lpDib variable. The caller must free the memory by calling
> CoTaskMemFree.

When I research memory management I just keep coming across the python garbage
collector is the best thing since sliced pie, and you doing something wrong if
you trying to clear up memory.

This is the line that creates memory that does not get released:

    
    
    lpDib = vmr_windowless_control.GetCurrentImage()
    

Where **vmr_windowless_control** comes from:

    
    
    vmr_windowless_control = vmr_config.QueryInterface(IVMRWindowlessControl)
    

Where **vmr_config** comes from:

    
    
    vmr_config = self.filter.QueryInterface(IVMRFilterConfig)      
    vmr_config.SetRenderingMode(Renderer.VMRMode[vmrmode]
    

Where **IVMRFilterConfig** comes from COMtype DirectShowLib import:

    
    
    try:
        from comtypes.gen.DirectShowLib import (ICreateDevEnum, IBaseFilter, IBindCtx,
                                                IMoniker, IFilterGraph,
                                                IVMRFilterConfig,
                                                IVMRWindowlessControl, IAMCrossbar,
                                                IAMTVTuner, IAMStreamConfig,
                                                IAMVideoProcAmp, IFilterMapper2)
    except ImportError:
        GetModule("DirectShow.tlb") # Create gen.DirectShowLib if it doesn't exist
        from comtypes.gen.DirectShowLib import (ICreateDevEnum, IBaseFilter, IBindCtx,
                                                IMoniker, IFilterGraph,
                                                IVMRFilterConfig,
                                                IVMRWindowlessControl, IAMCrossbar,
                                                IAMTVTuner, IAMStreamConfig,
                                                IAMVideoProcAmp, IFilterMapper2)
    

No idea how to attack this, brain is fried. Thanks in advance for any help or
leads.


Answer: Just needed to add the following:

    
    
    from ctypes import windll
    windll.ole32.CoTaskMemFree(lpDib)
    

Thank guys

