我正在尝试理解Python C-API的工作原理,并希望在Python和C扩展之间交换numpy数组。
因此,我开始学习这个教程:http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html 我尝试了那里的第一个示例,一个计算2D numpy数组迹的C模块,对我来说非常有用,因为我也想在2D数组中进行基本操作。
模块的名称是trace,并且它是使用setup.py文件编译的:
文件已编译,trace.so已在IPython中导入,但是当我尝试使用方法trace()时,出现了Segmentation Fault错误,我不知道原因。
我使用Fedora 15、Python 2.7.1、gcc 4.3.0、Numpy 1.5.1运行此代码。
因此,我开始学习这个教程: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()时,出现了Segmentation Fault错误,我不知道原因。
我使用Fedora 15、Python 2.7.1、gcc 4.3.0、Numpy 1.5.1运行此代码。
#include "Numpy/arrayobject.h"
吗? - mehmet.ali.anil