[Numpy-discussion] Initializing array from buffer
Andrea Arteaga
andyspiros at gmail.com
Sat Nov 22 19:57:05 EST 2014
Thanks everybody for suggesting many different ways to achieve this result.
While all of them seem valid methods, I decided to use the constructor, as
proposed by Robert:
> The np.ndarray constructor
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html> takes
a strides argument argument, and a buffer.
I could easily do this from within C++ in a clean way and without making
use of Numpy-specific C code. It sounds just a bit redundant to me the fact
that you have to provide the strides and the shape, even if the buffer
object already contains this information, but I suppose this is done so to
support an older buffer protocol, where only 1D arrays could be defined.
I have it working.
Thanks once more.
All the best
Andrea
2014-11-22 4:04 GMT+01:00 Sturla Molden <sturla.molden at gmail.com>:
> 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
>
>
>
>
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141123/16324bec/attachment.html>
More information about the NumPy-Discussion
mailing list