[Numpy-discussion] ndarray of object dtype

Ioan Ferencik ioan.ferencik@tkk...
Thu Oct 7 10:09:19 CDT 2010


Hello Robert,

I dare to bother you again with some  questions.

this time I have a numpy array with fields
ar = array([(1.0, 2.0, 3, 4), (2.0, 3.0, 4, 5)], dtype={'names':  
['q','wl','cssid','br'], 'formats':['f4', 'f4', 'i4', 'i4'],  
'offsets': [0, 4, 8, 12]}, order='F')

on C API I want to match this struct
typedef struct val1{
	float q;
	float wl;
	int cssid;
	int br;
}hm1dval1;

to an element of this array
I get the array object, i can see the fields. The type of the array  
elements is Pyarray_VOID

however following code gives me a segfault

hm1dval1 **s = PyArray_DATA(ao);

fprintf(stdout, "q is %d\n", (**s).cssid);

I also tried to use PyArray_BYTES but it failed too

I was thinking to add 4 bytes to PyArray_DATA(ao) for each member of  
the struct and for each elem of the array and cast those pointers to  
the float, float respectively int, int values but that failed too.

Can you see what am I doing wrong?



Quoting Robert Kern <robert.kern@gmail.com>:

> On Mon, Oct 4, 2010 at 00:41, Ioan Ferencik <ioan.ferencik@tkk.fi> wrote:
>> Hello list,
>>
>> I am trying to pass elements of a custom defined with C API.
>> I have successfully wrapped a type around a C struct.
>> I intent to create a list with these objects and process it using   
>> numpy C API.
>> So i  create an array:
>>
>> array = (PyArrayObject *)PyArray_ContiguousFromObject(input,
>> PyArray_OBJECT, 0, 0);
>>
>> to my understanding each el. in this array is a pointer to my type so
>> a cast to this type
>> should work.
>>
>>
>> this is my custom type
>>
>> typedef struct val{
>>         PyObject_HEAD
>>         float q;
>>         float wl;
>>         int cssid;
>>         int br;
>> }hm1dval;
>>
>> I am passing only one element for testing purposes.
>>
>> in python
>> a = [hm1d1.hm1dval() for i in range(0,1)]
>> for c in a:
>>         c.set_values(q=3.0, wl=2.5, cssid=6, br=7)
>>
>>
>> So following code should be valid in C:
>>
>> hm1dval s* = PyArray_DATA(array);
>>
>> but the members are 0 after casting in spite they were set previously.
>
> The elements of a dtype=object array are PyObject* pointers. In C, an
> array of pointers would look like this:
>
> hm1dval **s = PyArray_DATA(array);
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless
> enigma that is made terrible by our own mad attempt to interpret it as
> though it had an underlying truth."
>   -- Umberto Eco
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



Ioan Ferencik
PhD student
Aalto University
School of Science and Technology
Faculty Of Civil and Env. Engineering
Lahti Center
Tel: +358505122707




More information about the NumPy-Discussion mailing list