[Matrix-SIG] Accessing raw data in PyArrays from C

Edward C. Jones edcjones@erols.com
Wed, 10 Mar 1999 05:25:23 -0500

I have been writing some C code that extends NumPy. I find myself
regularly using the C macro:

#define ARRAYDATUM(type,charptr) (*( ((type) *) (charptr)))

to access the data in the array. For example, suppose "pao" is a
pointer to a PyArrayObject holding unsigned chars. Then

ARRAYDATUM(unsigned char, pao->data)

returns the first byte of data in the array. But this macro
assumes I know the type of the array.

In arraytypes.c, there are functions like (using UBYTE as an

static PyObject * UBYTE_getitem(char *ip)
 {return PyInt_FromLong((long)*((unsigned char *)ip));}

static int UBYTE_setitem(PyObject *op, char *ov)
 {*((unsigned char *)ov)=PyInt_AsLong(op);return PyErr_Occurred()
? -1:0;}

I suggest that something like the following be added:

static unsigned byte UBYTE_getraw(char *ip)
 {return *((unsigned char *)ip);}

static int UBYTE_setraw(unsigned cahr b, char *ov)
 {*((unsigned char *)ov)=b;}

How can this be done?

  Ed Jones