From 0ee6dedb7fb8deabf5e058de82084ff72ae5cd2e Mon Sep 17 00:00:00 2001
From: Gabriel Studer <gabriel.studer@unibas.ch>
Date: Thu, 20 Jan 2022 19:02:31 +0100
Subject: [PATCH] resolve segfault in dng observed with Python 3.9

Calling the PythonInterpreter constructor set up some Python objects via
Boost Python before Python was properly initialized. This caused a segfault
in _PyObject_GC_Malloc in Python. Not sure what finally triggered that
segfault. Different Boost version? Different Python version? Different
compiler? Bruce Lee beating up Chuck Norris? https://youtu.be/HFm2L03AetU
---
 modules/gui/src/python_shell/python_interpreter.cc        | 3 +++
 modules/gui/src/python_shell/python_interpreter_worker.cc | 2 +-
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/modules/gui/src/python_shell/python_interpreter.cc b/modules/gui/src/python_shell/python_interpreter.cc
index 93c9af99b..4c2afae41 100644
--- a/modules/gui/src/python_shell/python_interpreter.cc
+++ b/modules/gui/src/python_shell/python_interpreter.cc
@@ -66,6 +66,9 @@ PythonInterpreter::~PythonInterpreter()
 
 PythonInterpreter& PythonInterpreter::Instance()
 {
+  if(!Py_IsInitialized()){
+    Py_InitializeEx(1);
+  }
   static PythonInterpreter instance;
   return instance;
 }
diff --git a/modules/gui/src/python_shell/python_interpreter_worker.cc b/modules/gui/src/python_shell/python_interpreter_worker.cc
index c65a6d002..287660144 100644
--- a/modules/gui/src/python_shell/python_interpreter_worker.cc
+++ b/modules/gui/src/python_shell/python_interpreter_worker.cc
@@ -20,6 +20,7 @@
 
 #include "python_interpreter_worker.hh"
 #include "python_interpreter.hh"
+#include <iostream>
 
 namespace ost { namespace gui {
 
@@ -55,7 +56,6 @@ PythonInterpreterWorker::PythonInterpreterWorker():
   current_id_(),
   awake_(false)
 {
-  Py_InitializeEx(1);
   parse_expr_cmd_=bp::import("parser").attr("expr");
   main_namespace_ = bp::extract<bp::dict>(bp::import("__main__").attr("__dict__"));
   repr_=bp::import("__main__").attr("__builtins__").attr("repr");
-- 
GitLab