Segfault当试图从C调用一个Python函数 [英] Segfault when trying to call a Python function from C

查看:213
本文介绍了Segfault当试图从C调用一个Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想从C调用一个Python回调函数。

So, I want to call a Python callback function from C.

在某种程度上,函数被发送到C并打包成一个元组, p>

At some point, the function is sent to C and packed into a tuple like this

PyObject *userData = Py_BuildValue("Oi",py_callback,some_number);

在该区域的某处,我做 Py_INCREF(py_callback)

稍后在程序中,我想调用该函数。

Somewhere in that area, I do Py_INCREF(py_callback), too.
At some later time in the program, I want to call that function

PyObject *py_callback;
int some_number;
PyArg_ParseTuple((PyObject*)userData,"Oi",&py_callback,&some_number); // returns true
PyObject *py_result = PyObject_CallFunctionObjArgs(py_callback,
                                                   /* ... */
                                                   NULL);

,最后一次调用会引发分段错误。

and that last call throws a segmentation fault. Do you have any idea, why it would do such a thing?

推荐答案

当从Python C API中获取奇怪的行为时,总是值得仔细检查你正确地管理全局解释器锁(也称为GIL)的状态: http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock

When getting weird behaviour from the Python C API, it is always worth double checking that you are managing the state of the Global Interpreter Lock (aka "the GIL") correctly: http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock

这篇关于Segfault当试图从C调用一个Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆