call python from c -> pass and return arrays/lists

Diez B. Roggisch deets at nospam.web.de
Thu Apr 10 12:23:56 CEST 2008


Pieter wrote:

> Hi all,
> 
> I'm trying to call a python function from c. I need to pass an
> 2D-array to python and the python function returns a 2D-list back to
> c. I googled arround and I found how to pass ints/strings/... back and
> forth, but didn't find anything on passing arrays.
> 
> For an int it's as simple as this:
> 
> PyArg_Parse(ret,"i#", &my_long);
> 
> But I hacve no idea how to parse python lists to a c-array?

You return a list, parse that as object, and then work with the
sequence-protocol on them.

UNTESTED:

PyArg_Parse(ret,"o", &the_list);
if(PySequence_Check(the_list) {
  int size = PySequence_Size(the_list);
  int *result = malloc(sizof(int) * size);
  for(int i = 0; i < size; i++) {
     PyObject *item = PySequence_GetItem(the_list, i);
     if(PyInt_Check(item)) {
       result[i] = PyInt_AsLong(item);
     } else {
       return NULL;
     }
  }



Diez



More information about the Python-list mailing list