[英]Numpy C-Api example gives a SegFault
I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension. 我试图理解Python C-Api是如何工作的,我想在Python和C Extension之间交换numpy数组。
So, I started this tutorial: http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html 所以,我开始了这个教程: http : //dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html
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. 试图在那里做第一个例子,计算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);
}
}
The module's name is trace, and it is compiled with the setup.py file: 模块的名称是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])
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. 文件是编译的,trace.so是在IPython中导入的,但是当我尝试使用方法trace()时,我得到了一个Segmentation Fault,我不知道为什么。
I run this with Fedora 15, Python 2.7.1, gcc 4.3.0, Numpy 1.5.1 我用Fedora 15,Python 2.7.1,gcc 4.3.0,Numpy 1.5.1运行它
Your init function for the module needs to call 您的模块的init函数需要调用
import_array();
after 后
(void) Py_InitModule("trace", TraceMethods);
It mentions this in the tutorial near the top, but it is easy to miss. 它在顶部附近的教程中提到了这一点,但很容易错过。 Without this, it segfaults on PyArray_ContiguousFromObject
. 没有它,它会在PyArray_ContiguousFromObject
上发生段PyArray_ContiguousFromObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.