extending Python - passing nested lists

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 29 13:30:11 EST 2008


On Jan 29, 4:00 pm, Christian Meesters <meest... at uni-mainz.de> wrote:
> > You didn't mention speed in your original post.
>
> Sorry, perhaps I considered this self-evident - which it is, of course, not.
>
> > What about using
> > array.array?  Unless I am mistaken, these are just a thin wrapper
> > around normal C arrays.
>
> The algorithm I want to implement requires several million floating point
> operations. Neither the array-modules nor numpy's thin layer seem thin
> enough for me. ;-)

I'm not sure I understand.  Here, taken from Modules/arraymodule.c, is
the definition of an arrayobject:

typedef struct arrayobject {
	PyObject_VAR_HEAD
	char *ob_item;
	Py_ssize_t allocated;
	struct arraydescr *ob_descr;
	PyObject *weakreflist; /* List of weak references */
} arrayobject;

Now here is the function that gets an item from an array of floats:

static PyObject *
f_getitem(arrayobject *ap, Py_ssize_t i)
{
	return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
}

This means that if you define an array of floats, call the arrayobject
'ap', then (float *)ap->ob_item seems to meexactly what you want: a c
array of floats.  In what way is this not suitable?

> > Anyway you could always convert your list
> > into a c array, do lots and lots of fast calculations, then convert it
> > back again to a list.
>
> I guess I am too blind to see, but I couldn't discover a method description
> like "double* PyList_toDouble". So, yes, my question is a C-API-newbie
> question: What is the way to say "myCarray = SomePyMethod(InputPyList)"? Or
> better, what should be here instead
> static PyObject *_foo(PyObject *self, PyObject *args) {
>   double *v;
>   if (!PyArg_Parse(args, "(d)", &v))
>     return NULL;
> to get a list as an array of doubles into 'v' (and back to Python)?

You can always iterate over the elements of the list an fill your c
array with the results.  Look at the array_fromlist() function in
arraymodule.c, this function does exactly this.

HTH

--
Arnaud




More information about the Python-list mailing list