简体   繁体   中英

PyObject_CallObject crashed when called out of main function scope

I'm building a simple module to wrap a C function. The main function of this module ( test_wrapper ) basically receives a python function and call it:

#include <Python.h>

static PyObject* test_wrapper(PyObject* self, PyObject* args) {
    PyObject* py_handler;
    int args_ok = PyArg_ParseTuple(args, "O", &py_handler);

    PyObject_CallObject(py_handler, NULL);

    return Py_BuildValue("i", 0);
}

static PyMethodDef TestModuleMethods[] = {
    { "test", test_wrapper, METH_VARARGS, NULL },
    { NULL, NULL, 0, NULL }
};

static struct PyModuleDef TestModule = {
    PyModuleDef_HEAD_INIT,
    "test_module",
    NULL,
    -1,
    TestModuleMethods
};

PyMODINIT_FUNC PyInit_test_module(void) {
    return PyModule_Create(&TestModule);
}

The code above works fine. The thing is, let's suppose I need to call the passed python function ( py_handler ) in the future in another way, by a signal handler, for example, and now it expects an integer as an argument:

PyObject* py_handler;

void handler(int signo) {
    PyObject* handler_args = PyTuple_Pack(1, PyLong_FromLong(signo));
    PyObject_CallObject(py_handler, handler_args); //seg fault
}

static PyObject* test_wrapper(PyObject* self, PyObject* args) {
    int args_ok = PyArg_ParseTuple(args, "O", &py_handler);
    //Py_INCREF(py_handler); //adding this didn't work

    //calls sigaction to set handler function

    return Py_BuildValue("i", 0);
}

By doing this, PyObject_CallObject crashes (seg fault) when it's called by handler .

What could I be missing here?

If relevant, I'm building the .so with setup.py .

Acquiring and releasing GIL was enough to solve the problem:

void handler(int signo) {
    PyGILState_STATE state = PyGILState_Ensure();
    PyObject* handler_args = PyTuple_Pack(1, PyLong_FromLong(signo));
    PyObject_CallObject(py_handler, handler_args);
    PyGILState_Release(state);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM