[Numpy-discussion] numpy ndarray questions

Sturla Molden sturla at molden.no
Tue Jan 27 08:16:32 EST 2009


On 1/27/2009 12:37 PM, Sturla Molden wrote:

> import ctypes
> import numpy
> 
> fftw_malloc = ctypes.cdll.fftw.fftw_malloc
> fftw_malloc.argtypes = [ctypes.c_ulong,]
> fftw_malloc.restype = ctypes.c_ulong
> 
> def aligned_array(N, dtype):
>      d = dtype()
>      address = fftw_malloc(N * d.nbytes) # restype = ctypes.c_ulong
>      if (address = 0): raise MemoryError, 'fftw_malloc returned NULL'
>      class Dummy(object): pass
>      d = Dummy()
>      d.__array_interface__ = {
>          'data' = (address, False),
>          'typestr' : dtype.str,
>          'descr' : dtype.descr,
>          'shape' : shape,
>          'strides' : strides,
>          'version' : 3
>      }
>      return numpy.asarray(d)


Or if you just want to use numpy, aligning to a 16 byte boundary
can be done like this:


def aligned_array(N, dtype):
     d = dtype()
     tmp = numpy.array(N * d.nbytes + 16, dtype=numpy.uint8)
     address = tmp.__array_interface__['data'][0]
     offset = (16 - address % 16) % 16
     return tmp[offset:offset+N].view(dtype=dtype)


S.M.


















More information about the NumPy-Discussion mailing list