Numpy C-API 示例出现 SegFault

9 投票
1 回答
4509 浏览
提问于 2025-04-17 04:06

我正在尝试理解Python的C接口是怎么工作的,我想在Python和C扩展之间交换numpy数组。

所以,我开始看这个教程: http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html

我试着做那里的第一个例子,一个C模块,用来计算二维numpy数组的迹,这对我来说很有意思,因为我也想在二维数组上进行一些基本操作。

#include <Python.h>
#include "Numeric/arrayobject.h"
#include<stdio.h>

int main(){
Py_Initialize();
import_array();
}

static char doc[] =
"This is the C extension for xor_masking routine";

    static PyObject *
    trace(PyObject *self, PyObject *args)
    {
    PyObject *input;
    PyArrayObject *array;
    double sum;
    int i, n;

    if (!PyArg_ParseTuple(args, "O", &input))
    return NULL;
    array = (PyArrayObject *)
    PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 2, 2);
    if (array == NULL)
    return NULL;

    n = array->dimensions[0];
    if (n > array->dimensions[1])
    n = array->dimensions[1];
    sum = 0.;
    for (i = 0; i < n; i++)
    sum += *(double *)(array->data + i*array->strides[0] + i*array->strides[1]);
    Py_DECREF(array);
    return PyFloat_FromDouble(sum);
    }

static PyMethodDef TraceMethods[] = {
    {"trace", trace, METH_VARARGS, doc},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittrace(void)
{
    (void) Py_InitModule("trace", TraceMethods);
}


}

这个模块叫做trace,它是通过setup.py文件来编译的:

from distutils.core import setup, Extension

module = Extension('trace', sources = ['xor_masking.cpp'])
setup(name = 'Trace Test', version = '1.0', ext_modules = [module])

文件编译完成后,trace.so在IPython中被导入,但当我尝试使用trace()这个方法时,出现了段错误,我不知道为什么。

我是在Fedora 15上运行的,Python版本是2.7.1,gcc版本是4.3.0,Numpy版本是1.5.1。

1 个回答

17

你这个模块的初始化函数需要在

import_array();

之后调用

(void) Py_InitModule("trace", TraceMethods);

教程的开头有提到这一点,但很容易被忽略。如果不这样做,程序会在 PyArray_ContiguousFromObject 这里崩溃。

撰写回答