[Numpy-discussion] Re: View on same data with different type
Florian Schulze
florian.proff.schulze at gmx.net
Fri Dec 3 06:54:02 EST 2004
On Thu, 02 Dec 2004 21:49:10 +0100, Florian Schulze
<florian.proff.schulze at gmx.net> 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?
> 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?
>
> Regards,
> Florian Schulze
Hi again!
Todd Miller explained me how to do it (though it wasn't working as is, I
figured it out). As I think it is interesting to other people, I post it
here:
>>> import numarray
>>> a = numarray.arrayrange(12, type='i1')
# We can now create an array pointing to the same memory location with
different type:
>>> b = numarray.array(sequence=a._data, shape=(3,), type='i4')
# The key here is to use a._data. You have to specify the shape, or else
it doesn't work.
>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], type=Int8)
>>> b
array([ 50462976, 117835012, 185207048])
>>> a[3] = 10
>>> a
array([ 0, 1, 2, 10, 4, 5, 6, 7, 8, 9, 10, 11], type=Int8)
>>> b
array([167903488, 117835012, 185207048])
# Here you see how the assignment to a also changed b.
>>> a._data
<memory at 0x01031878 with size:0x0000000c held by object 0x00bcab40
aliasing object 0x00000000>
>>> b._data
<memory at 0x01031878 with size:0x0000000c held by object 0x00bcab40
aliasing object 0x00000000>
# Here you see that both arrays really point to the same memory location.
I tried it with numarray.records.array and it's basically the same, though
you have to use 'buffer' instead of 'sequence'.
I will have to try it out with mmap, but Todd told me it should be no
problem.
He also told me it could also be done with views by calling .view() on the
array and then set the other values (_type, _shape, _itemsize, [_strides,
_bytestride]) but I think this is more error prone and I didn't test it.
Thanks again to Todd Miller.
Regards,
Florian Schulze
More information about the NumPy-Discussion
mailing list