在Numpy数组上调用PyArg_ParseTuple时崩溃 [英] Crash when calling PyArg_ParseTuple on a Numpy array

查看:501
本文介绍了在Numpy数组上调用PyArg_ParseTuple时崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C语言编写了一个简单的Python扩展函数,该函数只读取一个Numpy数组,然后崩溃.

I wrote a simple Python extension function in C that just reads a Numpy array and it crashes.

static PyObject *test(PyObject *self, PyObject *args)
{
    PyArrayObject *array = NULL;

    if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &array)) // Crash
        return NULL;

    return Py_BuildValue("d", 0);
}

这里是怎么称呼的:

l = np.array([1,2,3,1,2,2,1,3])

print("%d" % extension.test(l))

我的代码怎么了?

推荐答案

我认为错误出在您未包含在示例中的代码中:您是否记得在模块初始化函数中调用了import_array():

I think the error is in the code you did not include in your example: have you remembered to call import_array() in your module init function:

...此子例程还必须包含对import_array()和/或import_ufunc()的调用,具体取决于所需的C-API.一旦实际调用任何C-API子例程,忘记放置这些命令将显示为丑陋的分段错误(崩溃).

... this subroutine must also contain calls to import_array() and/or import_ufunc() depending on which C-API is needed. Forgetting to place these commands will show itself as an ugly segmentation fault (crash) as soon as any C-API subroutine is actually called.

http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html#required-subroutine

我逐字复制并添加了示例(使用python 3)

I copied your example verbatim and added (using python 3)

PyMODINIT_FUNC
PyInit_numpytest(void)
{
    import_array();
    return PyModule_Create(&numpytest);
}

,该示例运行没有问题.另一方面,删除呼叫会导致崩溃.

and the example ran without issues. Removing the call on the other hand produces a crash.

这篇关于在Numpy数组上调用PyArg_ParseTuple时崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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