In a C extension to my Python program, I am trying to improve performance by setting two of the inputs to the main C function (which is called millions of times) as global variables, as they don't change often, so that I don't have to keep supplying them from Python using a lambda wrapper to the C function (which wastes a nontrivial amount of time). My code looks like this. First I declare the global variables at the top of the file:
unsigned char* splitArray;
PyObject* wordCmp;
Then the Python API function to set them:
static PyObject* py_set_globals(PyObject *self, PyObject *args)
{
free(wordCmp);
free(splitArray);
char* splitChars;
PyObject* wordC;
if (!PyArg_ParseTuple(args, "sO", &splitChars, &wordC))
return NULL;
wordCmp = (PyObject*)malloc(sizeof(PyObject));
memcpy(wordCmp, wordC, sizeof(PyObject));
splitArray = splitchars_to_mapping(splitChars);
return Py_BuildValue("");
}
In this case, splitArray is assigned to a 128-character array which is malloc'ed in the function splitchars_to_mapping, and wordCmp is a Python function object that is passed to C. Anyway, as far as I can tell, the char* splitArray works fine as a global variable, but when I later try to call wordCmp using PyEval_CallObject, Python/C crashes. So I have two questions:
- Why doesn't C crash immediately when I try to free the uninitialized pointers wordCmp and splitArray at the beginning of the function?
- Why am I unable to call wordCmp later when I have properly stored it on the heap and saved a reference to it as a global?