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

Pieter pieter.cogghe at gmail.com
Thu Apr 10 08:55:30 EDT 2008


Thanks, this did the trick:

            PyArg_Parse(ret,"O", &the_list);
            if (PySequence_Check(the_list)) {
             int size = PySequence_Size(the_list);
             int *result = malloc(sizeof(int) * size);
             int i;
             for (i = 0; i < size; i++) {
                PyObject *item = PySequence_GetItem(the_list, i);
                if(PyInt_Check(item)) {
                  result[i] = PyInt_AsLong(item);
                  printf("value %d: %d", i, result[i]);
                } else {
                    printf("Didn't work, NO INT");
                }
             }
            }

kind regards,

Pieter

---------- Doorgestuurd bericht ----------
From: "Diez B. Roggisch" <deets at nospam.web.de>
To: python-list at python.org
Date: Thu, 10 Apr 2008 12:23:56 +0200
Subject: Re: call python from c -> pass and return arrays/lists
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

-- 
Pieter Cogghe
Ganzendries 186
9000 Gent
0487 10 14 21



More information about the Python-list mailing list