9

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

所以,我开始了这个教程:http ://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html

尝试在那里做第一个例子,一个计算二维 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);
}


}

该模块的名称是 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 运行它

4

1 回答 1

17

您的模块的 init 函数需要调用

import_array();

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

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

于 2011-10-11T20:37:29.457 回答