将 python 嵌入我的应用程序时出现内存泄漏

Memory leak when embedding python into my application

以下程序在 python 2.7.13 和 运行 Windows 10 上缓慢但稳定地泄漏内存。

#include <Python.h>
#include <iostream>

int main()
{
    std::cout << "Python version: " << PY_VERSION << std::endl;

    while (true)
    {
        Py_Initialize();
        //PyGC_Collect();
        Py_Finalize();
    }

    return 0;
}

有趣的是,似乎并不是每次迭代都会泄漏内存。不过,我看到的是 python 打印的引用计数在每次迭代中缓慢增加(非常量)计数大约 90,而不管泄漏如何。使用 Visual Studio 诊断工具,我发现泄漏来自对 PyImport_ImportModule() 的调用,当它从磁盘读取编译模块时(实际调用堆栈有几层深)。

是否需要任何我不知道的额外清理步骤?还是 Python 垃圾收集器有什么可能导致这种情况,而不是 "real" 内存泄漏?

Py_Finalize — Python/C API Reference Manual(强调我的):

<...>
Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

以上答案综合起来

#include <Python.h>


int main(int argc, char *argv[])
{
    Py_Initialize();
    wchar_t *name = Py_DecodeLocale(argv[0], NULL);
    Py_SetProgramName(name); 
    
    pythonlovesC();

    Py_Finalize();
    return 0;
}

void pythonlovesC()
{

    while (true)
    {
       // do your python stuff here  
       PyGC_Collect();
        
    }

}