[Numpy-discussion] View on same data with different type

Todd Miller jmiller at stsci.edu
Thu Dec 2 16:25:43 EST 2004


On Thu, 2004-12-02 at 15:49, Florian Schulze wrote:
> Hi!
> 
> I would like to be able to access the same array (memory location) with 
> arrays of different size and with different typecodes. Let's say I have an 
> array of 8 UInt8 and I want to view it as 2 UInt32. I want to be able to 
> change the content of either array and the change should be visible in 
> both arrays. To speak in C notation, I want an *UInt8 and a *Uint32 to the 
> same memory location.
> Is that possible with Numeric or numarray, maybe even with slices of the 
> same data?

In numarray,  it is definitely possible to do what you want (in Python)
by accessing private attributes of the array: _data, _byteoffset,
_shape, _strides, _bytestride, _itemsize.  Given an array A,  one
approach would be to create an array B using buffer sharing and the
NumArray constructor like this:

>>> A = arange(100, type='Int8')
>>> B = NumArray(shape=(25,), buffer=A._data, type='Int32')

Another approach would be to use a view like this:

>>> B = A.view()
>>> B._type = Int32
>>> B._shape = (25,)
>>> B._itemsize = 4
# >>> B._strides = (4,)
# >>> B._bytestride = 4

> The reason I want this is that I want to prevent copying memory around. It 
> would be even cooler if this would work with mmaped arrays, though then 
> it's enough when it would work with read only mmaps. BTW, why isn't it 
> allowed to create overlapping mmap slices?

IIRC, since mmap slices are resizable,  permitting overlaps would have
complicated things...  so without a compelling need,  I/we decided to
KISS.

The kind of re-typing I showed above works for mmaps too... there's no
need to overlap since the same slice can be used in two different
arrays.

Todd

--=-fvu/cVmG8DY6+oRhVZR/--





More information about the NumPy-Discussion mailing list