Python C-Api の仕組みを理解しようとしており、Python と C 拡張機能の間で numpy 配列を交換したいと考えています。
そこで、このチュートリアルを開始しました: 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 で実行します