19

On the second call of the following code, my app segfault, so I guess I am missing something :

Py_Initialize();
pName = PyString_FromString("comp_macbeth");
pModule = PyImport_Import(pName);
Py_DECREF(pName);

if(pModule == NULL) {
    PyErr_Print();
    Py_Finalize();
    return;
}

pFunc = PyObject_GetAttrString(pModule, "compute");
/* pFunc is a new reference */

if (!pFunc || !PyCallable_Check(pFunc) ) {
    PyErr_Print();
    Py_Finalize();
    return;
}

Py_Finalize();

The comp_macbeth.py is importing numpy. If I remove the numpy import, everything is fine. Is it a numpy bug, or am I missing something about imports ?

shodanex
  • 14,975
  • 11
  • 57
  • 91

2 Answers2

17

From the Py_Finalize docs:

Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

Apparently Numpy is one of those. See also this message from Numpy-discussion.

Calling Py_Initialize() only once, and cleaning up at exit, is the way to go. (And it's should be faster, too!)

Petr Viktorin
  • 65,510
  • 9
  • 81
  • 81
  • I don't need to to the initialize / Finalize more than once, but I wanted to check if my understanding was correct – shodanex Oct 07 '11 at 11:41
  • I have the same problem 11 years later. Should have been enough time to fix this bug... https://stackoverflow.com/questions/74862962/exception-thrown-when-using-python-in-for-loop-in-c-script – Johan hvn Dec 21 '22 at 06:08
1

I have this in my module initialization part, but the URL does not exist anymore. In case it helps:

// http://numpy.scipy.org/numpydoc/numpy-13.html mentions this must be done in module init, otherwise we will crash
import_array();
eudoxos
  • 18,545
  • 10
  • 61
  • 110