PyObject segfault on function call

耗尽温柔 提交于 2019-12-01 11:40:13

Add PySys_SetArgv(argc, argv) (along with int argc, char **argv parameters to main), and your code will work.

tk.Tk() accesses sys.argv, which doesn't exist unless PySys_SetArgv has been called. This causes an exception which gets propagated out of get_ip and reported to Python/C by PyObject_CallObject returning NULL. The NULL gets stored to result and passed to PyString_AsString, which is the immediate cause of the observed crash.

Several remarks on the code:

  • It took effort to debug this because the code does no error checking whatsoever, it blindly presses forward until it crashes due to passing NULL pointers around. The least one can do is write something like:

    if (!ip_module_name) {
        PyErr_Print();
        exit(1);
    }
    // and so on for every PyObject* that you get from a Python API call
    

    In real code you wouldn't exit(), but do some cleanup and return NULL (or raise a C++-level exception, or whatever is appropriate).

  • There is no need to call PyGILState_Ensure in the thread that you already know holds the GIL. As the documentation of PyEval_InitThreads states, it initializes the GIL and acquires it. You only need to re-acquire the GIL when calling into Python from a C callback that comes from, say, the toolkit event loop that has nothing to do with Python.

  • New references received from Python need to be Py_DECREF'ed once no longer needed. Reference counting might be omitted from the minimal example for brevity, but it should always be minded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!