python - Numpy C-Api 示例给出了一个 SegFault

标签 python c numpy python-c-api

我正在尝试了解 Python C-Api 的工作原理,并且我想在 Python 和 C 扩展之间交换 numpy 数组。

因此,我开始了本教程:http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html

尝试在那里做第一个例子,一个计算 2d numpy 数组轨迹的 C 模块,对我来说非常简洁,因为我也想在 2d 数组中做基本操作。

#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 运行它

最佳答案

你的模块初始化函数需要调用

import_array();

之后

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

它在顶部附近的教程中提到了这一点,但很容易错过。没有这个,它会在 PyArray_ContiguousFromObject 上出现段错误。

关于python - Numpy C-Api 示例给出了一个 SegFault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7730717/

相关文章:

Python - 在满足多个条件的NumPy数组中选择行

python - 如何选择在 Python 中运行的类?

python - 从数据透视表 reshape /转换 Pandas 数据框

python - 面具下的 Numpy 标准偏差

c++ - 在 C 或 C++ (mac OSX) 中拥有 KeyDown 事件

c++ - "stdio"和 "stdlib"在 C 中代表什么?

python - 使用 Cython 的 bool numpy 数组

python - 使用装饰器停用功能

Powershell 中的 Python 2 和 3

c++ - PE文件解析c/c++