-
Notifications
You must be signed in to change notification settings - Fork 768
Closed
Labels
Description
I'm getting a memory leak with simple calls from .NET to Python function. The issue is reproducible on all pythonnet versions that I tested. When I test Python calls to .NET, then the memory leak is less obvious, since all resources are released when calling the CPython gc.collect(). Calling the same function from .NET does not release any resources, but calling the CLR GC.WaitForPendingFinalizers() blocks the execution.
>>> import clr
>>> import System
>>> for i in range(20000000):
... a=System.Double(i)
...
>>> import gc
>>> gc.collect()pyinclr.py
def testmethod():
return "abc"*3using System;
using Python.Runtime;
namespace memoryleakpykw
{
class Program
{
static void Main(string[] args)
{
PyObject pymodule;
PyObject gc;
PyObject testmethod;
PythonEngine.Initialize();
IntPtr pylock = PythonEngine.AcquireLock();
{
PyObject sys = PythonEngine.ImportModule("sys");// Py.Import("sys");
gc = PythonEngine.ImportModule("gc");// Py.Import("sys");
sys.GetAttr("path").InvokeMethod("append",
new PyString(@"C:\Users\denis.akhiyarov\source\repos\memoryleakpykw\pyinclr"));
pymodule = PythonEngine.ImportModule("pyinclr");
testmethod = pymodule.GetAttr("testmethod");
}
PythonEngine.ReleaseLock(pylock);
Console.WriteLine("starting test for memory leak, press any key");
Console.ReadKey();
pylock = PythonEngine.AcquireLock();
{
for (int i=1; i<=1000000; i++)
{
testmethod.Invoke();
}
}
gc.InvokeMethod("collect");
PythonEngine.ReleaseLock(pylock);
GC.Collect();
//GC.WaitForPendingFinalizers(); // this blocks execution
GC.Collect();
Console.WriteLine("finished test for memory leak, press any key");
Console.ReadKey();
}
}
}