我想了解Python C-Api是如何工作的,我想在Python和C扩展之间交换numpy数组。Numpy C-Api示例给出了一个SegFault
于是,我开始本教程:http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html
试图做第一个例子那里,计算2D numpy的阵列的跟踪C模块中,对我来说是很整齐,因为我想要做的基本操作也在二维数组中。
#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文件编译:
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
请注意,您所遵循的教程是* Numeric *,旧库被当前Numpy取代。 Numpy *主要*后向兼容,但不完全。 (是的,也*数字*被非正式称为“numpy的”,这种状况导致混乱...) –
然后,我应该导入 '#包括“与NumPy/arrayobject.h' 呢? –