Initializing a global PyObject * crashes while loading C++ extension
Created originally on Bitbucket by Hrvoje Nikšić
The attached module crashes when compiled and imported from pypy 5.10.0.
The crash is apparently triggered by global variable initialization:
#!c++ // global variable - crash goes away without it PyObject *global = PyInt_FromLong(42);
This kind of global initialization is frequently used in our in-house CPython C++ extensions. It is safe for dynamically loaded extensions because by the time the shared object gets dlopen-ed, Python has been initialized and the GIL acquired. In PyPy 5.10.0 it consistently crashes before executing the module initialization function.
Is this a bug in cpyext, or is the above pattern forbidden? Is there a workaround to make it work?
 The example is, of course, simplified - in actual code, the object would be a RAII wrapper object whose constructor invokes PyInt_FromLong. It is used in many different extensions and cannot be easily replaced with, say, a function that lazily constructs and returns an object.