[Numpy-discussion] Initializing array from buffer

Sturla Molden sturla.molden at gmail.com
Fri Nov 21 22:04:40 EST 2014


On 18/11/14 04:21, Robert McGibbon wrote:
> The np.ndarray constructor
> <http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html> takes
> a strides argument argument, and a buffer. Is it not sufficiently flexible?
>
> -Robert

AFAIK the buffer argument is not a memory address but an object 
exporting the old buffer protocol. We can abuse the __array_interface__ 
to do this though, but I prefer the C API functions. Wrapping a C 
pointer with __array_interface__ then becomes something like this (not 
tested, but should work):


import numpy as np

cdef class wrapper_array(object):

     cdef:
         object readonly __array_interface__	

     def __init__(wrapper_array self, addr, shape, dtype,
                    order, strides, offset):
         if strides is None:
             if order == 'C':
                 strides = None
             else:
                 strides = _get_fortran_strides(shape, dtype)
         self.__array_interface__ = dict(
             data = (addr + offset, False),
             descr = dtype.descr,
             shape = shape,
             strides = strides,
             typestr = dtype.str,
             version = 3,
         )

cdef object _get_fortran_strides(shape, dtype):
     strides = tuple(dtype.itemsize * np.cumprod((1,) + shape[:-1]))
     return strides

def wrap_pointer(void *addr, shape, dtype, order, strides, offset):
     """Wraps a C pointer with an ndarray"""
     return np.asarray(wrapper_array(<Py_uintptr_t> addr, shape,
        dtype, order, strides, offset))


https://github.com/sturlamolden/sharedmem-numpy/blob/master/sharedmem/array.py



Sturla


	






More information about the NumPy-Discussion mailing list