Access pointer to shape attribute of numpy array

51 views
Skip to first unread message

Ghislain Vaillant

unread,
Jan 9, 2015, 2:01:48 PM1/9/15
to pytho...@googlegroups.com
Hi everyone,

I am wrapping a function using CFFI with the following signature:

void c_compute(int ndim, const int *shape, double *data)

to a function which takes a Numpy array:

def py_compute(array)

and I want to extract d, n and data from the array parameter in an efficient way.

for ndim, I use array.ndim,
for data, I use array.ctypes.data and cast it to double* with an ffi.cast
for shape however, I am stuck.

I though about using something like:
ffi.cast('const int *', array.ctypes.shape_as(ctypes.c_int))

But the cast does not seem to be allowed. What am I missing ?

Cheers,
- Ghis


Armin Rigo

unread,
Jan 9, 2015, 5:19:23 PM1/9/15
to pytho...@googlegroups.com
Hi Ghis,

On 9 January 2015 at 20:01, Ghislain Vaillant <ghis...@gmail.com> wrote:
> I though about using something like:
> ffi.cast('const int *', array.ctypes.shape_as(ctypes.c_int))
>
> But the cast does not seem to be allowed. What am I missing ?

You can pass a regular list or tuple of integers to a function's
"int *" argument (which is equivalent to "int[]"). I don't know numpy
but I'm sure you can read this information easily from the array.


A bientôt,

Armin.

Ghislain Vaillant

unread,
Jan 13, 2015, 9:12:27 AM1/13/15
to pytho...@googlegroups.com, ar...@tunes.org


Hi Armin, I followed your advice and used the following piece of code:

ffi.new('const int [%d]'%(array.ndim), array.shape)



and it worked as intended. Thanks for your help.

Cheers,
- Ghis

Armin Rigo

unread,
Jan 13, 2015, 9:15:12 AM1/13/15
to pytho...@googlegroups.com
Hi Ghis,

On 13 January 2015 at 15:12, Ghislain Vaillant <ghis...@gmail.com> wrote:
> ffi.new('const int [%d]'%(array.ndim), array.shape)

You can improve by doing only:

ffi.new('int []', array.shape)

or passing directly 'array.shape' as a function argument, without the
ffi.new() at all, provided 'array.shape' gives a tuple or a list.


A bientôt,

Armin.
Reply all
Reply to author
Forward
0 new messages