extending Python - passing nested lists

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 29 08:07:17 EST 2008


On Jan 29, 12:48 pm, Christian Meesters <meest... at uni-mainz.de> wrote:
> Think, that I'm still at the wrong track. Point is that I cannot find any
> examples and don't know where to start here.
> Perhaps my problem boils down to two questions:
> I'd like to pass lists (in some cases nested ones) from Python to C and
> convert those Python-lists to C-arrays (e. g. of doubles). My second wish
> is to return a C-array of longs to a Python list.
>
> My approach so far:
>
> static PyObject *_foo(PyObject *self, PyObject *args) {
>   double *v;
>   if (!PyArg_Parse(args, "(d)", &v))
>     return NULL;
>   // then I can't access v like v[1] ...

I'm not a C API guru and I may not understand properly what info you
are looking for but from http://docs.python.org/api/sequence.html:

PyObject* PySequence_GetItem( PyObject *o, Py_ssize_t i)

Return value: New reference.
Return the ith element of o, or NULL on failure. This is the
equivalent of the Python expression "o[i]".


>   <snip>
>   // then return *v
>   return with something like PyBuildValue (but didn't get so far)

This allows you to create a list (from http://docs.python.org/api/listObjects.html):

PyObject* PyList_New( Py_ssize_t len)

Return value: New reference.
Return a new list of length len on success, or NULL on failure. Note:
If length is greater than zero, the returned list object's items are
set to NULL. Thus you cannot use abstract API functions such as
PySequence_SetItem() or expose the object to Python code before
setting all items to a real object with PyList_SetItem().

...and this allows you to populate it (from http://docs.python.org/api/listObjects.html):

int PyList_Append( PyObject *list, PyObject *item)

Append the object item at the end of list list. Return 0 if
successful; return -1 and set an exception if unsuccessful. Analogous
to list.append(item).

>
> }
>
> Can somebody give me a hint here, please? Passing simple arguments to and
> fro (e. g. single integer values) is no problem, but lists of unknown size?

HTH

--
Arnaud



More information about the Python-list mailing list