I have to do Py_Initialize() and Py_Finalize() several times in my C++ application during process execution.
But the 2nd call to Py_Finalize() causes a crash if there is the PySide.QtCore module imported.
The shortest example:
The actual crash occurs on gcmodule.c:360
The op's type is likely to be inconsistent, as op->ob_type->tp_is_gc equals to 0xfbfbfbfbfb007075
I've tried the same for PyQt4.QtCore and it does not crash.
Got a similar error on Debian Linux (gcc (Debian 5.3.1-12), Python 2.7.6, PySide 1.2.1, Py_Finalize() crashes on the 4th call to it but there is a bit different callstack:
The actual crash occurs on typeobject.c:2643
Looks familiar, as there something went wrong in the garbage collector code.
Having reduced the initialization code of PySide.QtCore, I found that PySide::init(module); causes the issue. If I comment it out, it will work.
Went deeper, found that if I comment out MetaFunction::init(module); inside the PySide::init implementation this also will work fine. Found there in contrast to the other init function implementation (ClassInfo::init, Signal::init, Slot::init, Property::init), it DOES NOT incref a counter of its type (PySideMetaFunctionType).
I have fixed the issue on Linux. There is an error inside MetaFunction::init
Unfortunately, that fix didn't help to fix the crash on Windows.
I used the same approach to locate the problematic code on Windows. What I've found is that any call to Shiboken::Enum::createGlobalEnumItem inside the PySide.QtCore initialization function causes the following crash.
I'm not sure whether it's a proper fix (may lead to memory leaks) but:
There are two possible calls to Py_DECREF, that it calls decref twice for a single object. So that, I commented Py_DECREF out in the createGlobalEnumItem function, now it doesn't crash.
Another one issue that leads to an assertion failure on typeobject.c:2642
Of course, type there is the PySideMetaFunctionType instance.
Comparing to the similar types (such as the PySideSlotType), discovered that the tp_base of the PySideMetaFunctionType is NULL. PySideSlotType->tp_base is &PyType_Type.
Did the same for the PySideMetaFunctionType, now it's OK. I hope so. The code is so erratic!