[Numpy-discussion] Problem accessing elements of an array of dtype="O" from C

Travis E. Oliphant oliphant at enthought.com
Tue Feb 5 19:32:37 EST 2008


Chris Ball wrote:
> Hi,
>
> I'm having some trouble accessing elements in an array of dtype="O"
> from C code; I hope someone on the list could give me some advice
> (because I might be doing something stupid).
>
> I have an array of simple objects, created as follows:
>
> class CF(object):
>     def __init__(self,num=0.0):
>         self.num=num
>
> from numpy import array
> objs = array([[CF(0.0),CF(0.1),CF(0.2)],
>               [CF(1.0),CF(1.1),CF(1.2)]],dtype=object)
>
>
> I'd like to loop through this array and access the 'num' attribute of
> each CF object - but using C.
>  
> I have a C function (based on an example in the numpy book - 'Basic
> Iteration', page 312):
>
> double loop(PyObject* a_){
>
>   PyArrayIterObject *iter;
>   iter = (PyArrayIterObject *)PyArray_IterNew(a_);
>   
>   while (iter->index < iter->size) {
>       PyObject *cf = (PyObject *)(iter->dataptr);
>       PyObject *num_obj = PyObject_GetAttrString(cf,"num");
>       PyArray_ITER_NEXT(iter);
>   }
> return 0.0;
> }
>   
The problem here is that iter->dataptr should be re-cast to a PyObject 
** because what is contained at the memory location is a *pointer* to 
the PyObject.   Thus, you have to de-reference iter->dataptr to get the 
PyObject * that you want:

PyObject **cf = (PyObject **)PyArray_ITER_DATA(iter);
PyObject *num_obj = PyObject_GetAttrString(*cf, "num");
PyArray_ITER_NEXT(iter);

should do what you want.

-Travis O.




More information about the NumPy-Discussion mailing list