@@ -17,6 +17,7 @@ implementation
1717 TDelphiFunctions = class
1818 public
1919 class function is_prime (const N: Integer): Boolean; static;
20+ class procedure AfterModuleInit (Sender: TObject);
2021 end ;
2122
2223var
@@ -25,39 +26,53 @@ TDelphiFunctions = class
2526 gDelphiWrapper : TPyDelphiWrapper;
2627 DelphiFunctions: TDelphiFunctions;
2728
28-
29-
3029function PyInit_DemoModule : PPyObject;
31- var
32- Py : PPyObject;
3330begin
31+ if not Assigned(gEngine) then
3432 try
3533 gEngine := TPythonEngine.Create(nil );
3634 gEngine.AutoFinalize := False;
3735 gEngine.UseLastKnownVersion := True;
3836
37+ gDelphiWrapper := TPyDelphiWrapper.Create(nil );
38+ gDelphiWrapper.Engine := gEngine;
39+
40+ // !!It is important that the extension module is the last
41+ // Engine client created
3942 gModule := TPythonModule.Create(nil );
4043 gModule.Engine := gEngine;
4144 gModule.ModuleName := ' DemoModule' ;
4245
43- gDelphiWrapper := TPyDelphiWrapper.Create(nil );
44- gDelphiWrapper.Engine := gEngine;
46+ // Set IsExtensionModule so that the module is not created by Initialzize
47+ gModule.IsExtensionModule := True;
48+ gModule.MultInterpretersSupport := mmiPerInterpreterGIL;
49+ gModule.OnAfterInitialization := TDelphiFunctions.AfterModuleInit;
50+
4551 gDelphiWrapper.Module := gModule;
4652
4753 gEngine.LoadDllInExtensionModule;
48- Py := gDelphiWrapper.Wrap(DelphiFunctions, TObjectOwnership.soReference);
49- gModule.SetVar(' delphi_funcs' , Py);
50- gEngine.Py_DecRef(Py);
5154 except
55+ Exit(nil );
5256 end ;
53- Result := gModule.Module ;
57+
58+ // The python import machinery will create the python module from ModuleDef
59+ Result := gEngine.PyModuleDef_Init(@gModule.ModuleDef);
5460end ;
5561
5662{ TTestRttiAccess }
5763
5864
5965{ TDelphiFunctions }
6066
67+ class procedure TDelphiFunctions.AfterModuleInit (Sender: TObject);
68+ var
69+ Py : PPyObject;
70+ begin
71+ Py := gDelphiWrapper.Wrap(DelphiFunctions, TObjectOwnership.soReference);
72+ gModule.SetVar(' delphi_funcs' , Py);
73+ gEngine.Py_DecRef(Py);
74+ end ;
75+
6176class function TDelphiFunctions.is_prime (const N: Integer): Boolean;
6277// Naive implementation. It is just a demo...
6378begin
0 commit comments