# -*- Mode: Python -*- Not really, but close enough """Cython access to Numpy arrays - simple example. """ ############################################################################# # Load C APIs declared in .pxd files via cimport # # A 'cimport' is similar to a Python 'import' statement, but it provides access # to the C part of a library instead of its Python-visible API. See the # Pyrex/Cython documentation for details. cimport c_python as py cimport c_numpy as cnp # NOTE: numpy MUST be initialized before any other code is executed. cnp.import_array() ############################################################################# # Load Python modules via normal import statements import numpy as np ############################################################################# # Regular code section begins # A 'def' function is visible in the Python-imported module def print_array_info(cnp.ndarray arr): """Simple information printer about an array. Code meant to illustrate Cython/NumPy integration only.""" cdef int i print '-='*10 # Note: the double cast here (void * first, then py.Py_intptr_t) is needed # in Cython but not in Pyrex, since the casting behavior of cython is # slightly different (and generally safer) than that of Pyrex. In this # case, we just want the memory address of the actual Array object, so we # cast it to void before doing the py.Py_intptr_t cast: print 'Printing array info for ndarray at 0x%0lx'% \ (arr,) print 'number of dimensions:',arr.nd print 'address of strides: 0x%0lx'%(arr.strides,) print 'strides:' for i from 0<=iarr.strides[i] print 'memory dump:' print_elements( arr.data, arr.strides, arr.dimensions, arr.nd, sizeof(double), arr.dtype ) print '-='*10 print # A 'cdef' function is NOT visible to the python side, but it is accessible to # the rest of this Cython module cdef print_elements(char *data, py.Py_intptr_t* strides, py.Py_intptr_t* dimensions, int nd, int elsize, object dtype): cdef py.Py_intptr_t i,j cdef void* elptr if dtype not in [np.dtype(np.object_), np.dtype(np.float64)]: print ' print_elements() not (yet) implemented for dtype %s'%dtype.name return if nd ==0: if dtype==np.dtype(np.object_): elptr = (data)[0] #[0] dereferences pointer in Pyrex print ' ',elptr elif dtype==np.dtype(np.float64): print ' ',(data)[0] elif nd == 1: for i from 0<=idata)[0] print ' ',elptr elif dtype==np.dtype(np.float64): print ' ',(data)[0] data = data + strides[0] else: for i from 0<=i