[SciPy-user] Passing numpy array to a c function

Stéfan van der Walt stefan@sun.ac...
Sun Apr 20 16:19:14 CDT 2008

Hi Chris

On 20/04/2008, Christopher Brown <c-b@asu.edu> wrote:
>  I am trying to pass a numpy array of float64's to a c function, and I am
>  not having much luck. I have tried every example I could find, and based
>  on everything I have read, this seems (to me) like it should work.

Your example works perfectly over here.

>  #include "Python.h"
>  #include "Numeric/arrayobject.h"

You probably want

#include "numpy/arrayobject.h"

>  PyObject* my_c_function(PyObject* self, PyObject* args) {
>    PyArrayObject *array;
>    int i;
>    if (!PyArg_ParseTuple(args, "O|i", &array, &i))
>      return NULL;
>    printf("length is: %5.0f\n",i);
>    printf("type_num is: %3.0f\n",array->descr->type_num);

These should use "%d" instead of "%f".

In [5]: x = np.array([1,2,3])

In [6]: boo.my_c_function(x,len(x))
length is:     3
type_num is:   7

I attach the source code and setup.py file to build it:

python setup.py build_ext -i

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: boo.c
Url: http://projects.scipy.org/pipermail/scipy-user/attachments/20080420/b4bbce82/attachment.c 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: setup.py
Type: application/octet-stream
Size: 230 bytes
Desc: not available
Url : http://projects.scipy.org/pipermail/scipy-user/attachments/20080420/b4bbce82/attachment.obj 

More information about the SciPy-user mailing list