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

Chris Ball ceball@users.sourceforge....
Tue Feb 5 09:22:53 CST 2008


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;
}


I get a segmentation fault when I try to call loop(objs). (Commenting
out the 'PyObject_GetAttrString' line, I do not get a segmentation
fault.)  Using instead an array of floats and a very similar function,
I have no problems:

from numpy import array
objs = array([[1.0,2.0,3.0],[4.0,5.0,6.0]],dtype=float)

...

double loop(PyObject* a_){

  PyArrayIterObject *iter;
  iter = (PyArrayIterObject *)PyArray_IterNew(a_);
  
  while (iter->index < iter->size) {
      double *num = (double *)(iter->dataptr);    
      printf("%f\\n",*num);
      PyArray_ITER_NEXT(iter);
  }
return 0.0;
}


I am calling this C code via Instant [1]. I have previously written to
the SciPy-Dev mailing list about a strange (to me) indexing problem
using arrays of dtype='O' with Weave [2]; I believe that this is the
same problem (and that it is either with numpy, or with my
understanding of numpy, rather than with Weave or Instant).


Please could someone help me out?

If you think you could help if I were to give you a runnable example
of the problem in your own preferred way of calling C code from
Python, please let me know, and I can probably provide one.

Thanks,
Chris
        

[1] http://www.fenics.org/wiki/Instant
[2] http://thread.gmane.org/gmane.comp.python.scientific.devel/7198/focus=7264




More information about the Numpy-discussion mailing list