numpy的C-API的例子给出了一个段错误 [英] Numpy C-Api example gives a SegFault
问题描述
我想明白了Python C-API如何工作的,我想换Python和C扩展之间numpy的数组。
I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension.
于是,我开始本教程:<一href=\"http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html\">http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html
试图做第一个例子那里,计算2D numpy的阵列的痕迹C模块中,对我来说很整齐,因为我想在二维数组也做基本的操作。
Tried to do the first example there, a C module that calculates the trace of a 2d numpy array, was very neat for me, since I want to do elementary operations in 2d arrays also.
#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);
}
}
模块的名称是微量,而且它与setup.py文件编译
The module's name is trace, and it is compiled with the setup.py file:
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中,但是当我尝试使用方法跟踪(),我得到一个分段错误,我不知道为什么。
The file is compiled, trace.so is imported in IPython, but when I try to use the method trace(), I get a Segmentation Fault, I don't know why.
我这运行在Fedora 15的Python 2.7.1,GCC 4.3.0,1.5.1 numpy的
I run this with Fedora 15, Python 2.7.1, gcc 4.3.0, Numpy 1.5.1
推荐答案
该模块您init函数需要调用
Your init function for the module needs to call
import_array();
在
(void) Py_InitModule("trace", TraceMethods);
,提到这一点靠近顶部的教程,但很容易错过。没有这一点,它出现segfaults在 PyArray_ContiguousFromObject
。
这篇关于numpy的C-API的例子给出了一个段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!