Skip to content

Commit 78c3e0f

Browse files
committed
Add AppLifecycleListener to finalize Python on detach
Replaces flutter/foundation.dart with flutter/widgets.dart and adds an AppLifecycleListener to call Py_FinalizeEx when the app detaches. This ensures proper cleanup of the Python interpreter when the app lifecycle ends.
1 parent a272d79 commit 78c3e0f

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/serious_python_android/lib/src/cpython.dart

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import 'dart:ffi';
33
import 'dart:isolate';
44

55
import 'package:ffi/ffi.dart';
6-
import 'package:flutter/foundation.dart';
6+
import 'package:flutter/widgets.dart';
77
import 'package:path/path.dart' as p;
88

99
import 'gen.dart';
@@ -96,6 +96,16 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
9696
_debug("after Py_Initialize()");
9797
}
9898

99+
AppLifecycleListener(onDetach: () {
100+
_debug("AppLifecycleListener: onDetach");
101+
_withGIL(cpython, () {
102+
if (cpython.Py_IsInitialized() != 0) {
103+
cpython.Py_FinalizeEx();
104+
_debug("after Py_FinalizeEx()");
105+
}
106+
});
107+
});
108+
99109
final result = _withGIL(cpython, () {
100110
final logcatSetupError = _setupLogcatForwarding(cpython);
101111
if (logcatSetupError != null) {
@@ -149,8 +159,8 @@ String getPythonError(CPython cpython) {
149159
//_debug("Traceback module loaded");
150160

151161
final formatFuncName = "format_exception".toNativeUtf8();
152-
final pFormatFunc =
153-
cpython.PyObject_GetAttrString(tracebackModulePtr, formatFuncName.cast());
162+
final pFormatFunc = cpython.PyObject_GetAttrString(
163+
tracebackModulePtr, formatFuncName.cast());
154164
cpython.Py_DecRef(tracebackModuleNamePtr.cast());
155165

156166
if (pFormatFunc != nullptr && cpython.PyCallable_Check(pFormatFunc) != 0) {

0 commit comments

Comments
 (0)