[Numpy-discussion] Ctypes support in NumPy
oliphant.travis at ieee.org
Mon Jul 3 14:38:17 CDT 2006
Albert Strasheim wrote:
> Stefan and I did some more experiments and it seems like .ctypes.strides
> isn't doing the right thing for subarrays.
> For example:
> In : x = N.rand(3,4)
> In : [x.ctypes.strides[i] for i in range(x.ndim)]
> Out: [32, 8]
> This looks fine. But for this subarray:
> In : [x[1:3,1:4].ctypes.strides[i] for i in range(x.ndim)]
> Out: [32, 8]
> In this case, I think one wants strides (the row stride) to return 40.
Why do you think that?
All sliced arrays keep the same strides information as their
"parents". This is the essence of a "view". The striding is exactly
the same as before (the data hasn't moved anywhere), only the starting
point and the bounds have changed.
> .ctypes.data already seems to do the right thing:
> In : x.ctypes.data
> Out: c_void_p(31685288)
> In : x[1:3,1:4].ctypes.data
> Out: c_void_p(31685328)
> In : 31685288-31685328
> Out: 40
> What would be a good way of dealing with discontiguous arrays? It seems like
> one might want to disable their .ctypes attribute.
No, not at all. Discontiguous arrays are easily handled simply by using
the strides information to step through the array in each dimension
instead of "assuming" contiguousness.
Perhaps there is some confusion about what the strides actually represent.
It's quite easy to write C-code that takes stride information as well
which will then work with discontiguous arrays. The benefit of this
approach is that you avoid copying data when you don't really have to.
There should be very little performance penalty in most algorithms as
well as the strides calculation is not much more than adding 1 to the
More information about the Numpy-discussion