[Numpy-discussion] Numeric and swig (or, how to wrap functions).
Roger Hansen
rogerha at ifi.uio.no
Fri Jan 5 09:48:15 EST 2001
* Roy Dragseth
[snip Numeric and swig questions about how to give a numpy array to a
swigged c function]
> Any hints is greatly appreciated.
I've done this a few times. What you need to do is help swig
understand that a numpy array is input and how to treat this as a C
array. With swig you can do this with a typemap. Here's an example:
we can create a swig interface file like
%module exPyC
%{
#include <Python.h>
#include <arrayobject.h> /* Remember this one */
#include <math.h>
%}
%init %{
import_array() /* Initial function for NumPy */
%}
%typemap(python,in) double * {
PyArrayObject *py_arr;
/* first check if it is a NumPy array */
if (!PyArray_Check($source)) {
PyErr_SetString(PyExc_TypeError, "Not a NumPy array");
return NULL;
}
if (PyArray_ObjectType($source,0) != PyArray_DOUBLE) {
PyErr_SetString(PyExc_ValueError,
"Array must be of type double");
return NULL;
}
/* check that array is 1D */
py_arr = PyArray_ContiguousFromObject($source,
PyArray_DOUBLE, 1, 1);
/* set a double pointer to the NumPy allocated memory */
$target = py_arr->data;
}
/* end of typemap */
%inline %{
void arrayArg(double *arr, int n)
{
int i;
for (i = 0; i < n; i++) {
arr[i] = f(i*1.0/n);
}
}
%}
Now, compile your extension, and test
>>> import exPyC
>>> import Numeric
>>> a = Numeric.zeros(10,'d')
>>> a
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
>>> exPyC.arrayArg(a,10)
>>> a
array([ 0. , 0.00996671, 0.0394695 , 0.08733219, 0.15164665, 0.22984885,
0.31882112, 0.41501643, 0.51459976, 0.61360105])
You can also get rid of the length argument with a
typemap(python,ignore), see the swig docs. For more info about the
safety checks in the typemap check the numpy docs.
Lykke til! :-)
HTH,
Roger
More information about the NumPy-Discussion
mailing list