Jump to content
Sign in to follow this  
AndreasSt

Memory Leak creating Engine at runtime?

Recommended Posts

Hello,

I am Creating a TPythonEngine at runtime from code, excecute a script and then free all things again. In the task manager the memory of the app increases everytime I do this action.

So I think there is an error in my software. Perhaps I have forgotten a step.

I have done the test with the p4d installed by getit and as second version with the current master from github

Thanks a lot for any help.

procedure TForm1.Button1Click(Sender: TObject);
var
  myPythonEngine: TPythonEngine;
  pdvTest: TPythonDelphiVar;
  myScript:TStringlist;
begin
  myScript:=TStringlist.Create;
  myScript.Add('');
  myScript.Add('s="'+Edit1.Text+'"');
  myScript.Add('if s.find("g")>=0:');
  myScript.Add('    sTest.value="Good"');
  myScript.Add('    st="OK"');
  myScript.Add('else:');
  myScript.Add('    sTest.value="Bad"');
  myScript.Add('    st="NOK"');

  myPythonEngine:=TPythonEngine.Create(self);
  myPythonEngine.LoadDll;

  pdvTest:= TPythonDelphiVar.Create(myPythonEngine);
  pdvTest.VarName:= 'sTest';
  pdvTest.Module:='__main__';
  pdvTest.Engine:=myPythonEngine;
  pdvTest.Initialize;
  try
    myPythonEngine.ExecStrings(myScript);
  except on E: Exception do
    memo1.lines.add(E.Message);
  end;
  myscript.Free;
  memo1.Lines.Add(pdvTest.ValueAsString);
  pdvTest.Free;
  myPythonEngine.Free;
end;

 

Share this post


Link to post

Profile your application to identify memory issues. For example, with Deleaker, you can take a baseline snapshot before running your script and another one immediately after. By comparing these snapshots, you can explore which allocations were not freed. To be honest, I don't see any mistakes in your code, as you explicitly free all objects.

Share this post


Link to post

You can set ReportMemoryLeaksOnShutdown to True to see whether there are leaks on the Delphi side.

 

Loading and unloading the python dll multiple times is not a good idea.   There is no guarantee that it will release all allocated memory when it unloads and it does not unload all other dlls loaded by python.  It was designed to be loaded once in a single process. 

 

And there is no need to do that.  Your program will be faster and leaner if you reuse the python dll.

 

 

Edited by pyscripter

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×