[Numpy-discussion] ctypes and numpy

Sebastian Walter sebastian.walter at gmail.com
Tue Dec 7 09:15:24 EST 2010

Hello all,

I'd like to call a Python function from a C++ code. The Python
function has numpy.ndarrays as input.
I figured that the easiest way would be to use ctypes.

However,  I can't get numpy and ctypes to work together.

----------- run.c ------------
#include <Python.h>
#include <numpy/noprefix.h>

void run(PyArrayObject *y, PyObject *f) {
    npy_intp Ny = PyArray_SIZE(y);
------- end run.c ----------

-------- run.py ----------
import os, ctypes, numpy

_r = numpy.ctypeslib.load_library('librun.so', os.path.dirname(__file__))
_r.run.argtypes = [ctypes.py_object]
x = numpy.array([1,2,3.])

-------- end run.py ----------

Compiling gives me the warning:

gcc -o librun.so -I/usr/include/python2.6
-I/usr/lib/python2.6/dist-packages/numpy/core/include -O0 -fpic
-shared -Wall  run.c
run.c: In function ‘run’:
run.c:5: warning: unused variable ‘Ny’
run.c: At top level:
/usr/include/python2.6/numpy/__multiarray_api.h:968: warning:
‘_import_array’ defined but not used

and when I run it I get a segmentation fault.

I guess I'm not the first one who has this problem, but I couldn't
find something useful on the web.
Any pointers are suggestions are welcome.


More information about the NumPy-Discussion mailing list