[SciPy-dev] C API
oliphant at ee.byu.edu
Thu Nov 24 02:53:11 CST 2005
Nariman Habili wrote:
>I would like to know how to extract a value (eg int) from a PyObject that
>contains an ndarray. I'm using boost.python to expose classes to Python. I'm
>passing an ndarray to C++ by reference. However, since boost.python hasn't
>been updated yet to scipy core, I'm using the C API.
>I've tried PyArray_GETITEM, however it returns a PyObject, and I'm not sure
>how to extract an int or double etc from it. I need the C types so I can
>interface python with other parts of my code.
PyArray_DATA(obj) gives you a pointer to the first element of the ndarray.
This assumes that obj is actually an ndarray object, of course.
The data flag bits in PyArray_FLAGS(obj) are critical to dealing with
the data correctly.
It is possible that the data is not in machine byte order, not aligned
properly (which can cause
BUS errors on some platforms if you try certain operations), and not
writeable. Of course in C
you can do whatever you want, but if you don't respect the flags, you
may get gibberish and
even segfault your machine.
If PyArray_CHKFLAGS(obj, BEHAVED_FLAGS) is true then you don't have to
worry about the above paragraph, otherwise you do
How to get elements beyond the first depends on PyArray_STRIDES(obj) and
If PyArray_CHKFLAGS(obj, CARRAY_FLAGS) is true then access to elements
beyond the first is simple
as the data region is a simple contiguous chunk of memory with each
element placed right after the next in C-style contiguous fashion (last
index varies the fastest).
Otherwise you need to understand the concept of striding in order to
access elements beyond the first.
There is also the Array iterator which you can construct and use the
PyArray_ITER_GOTO() macro to jump to a particular element in the array
(regardless of the flags). If the array is not BEHAVED, then you need
to be careful about how you access it, but the dataptr field of the
array iterator structure will point to the right place.
So, is this all clear as mud? If you were more clear about which
element of the array you wanted and how the array was created, I could
be more directly helpful instead of exposing you to all the possibilities.
More information about the Scipy-dev