Unpacking a python list in C?

Ken Seehof kseehof at neuralintegrator.com
Thu May 2 13:37:55 EDT 2002


> I need some help with extending python in C. I want to call a function
> of a list from python:
> 
> 	answer = my_function(my_list)
> 
> where my_function is a function, and my_list is a python list of floats.
> I want my_function to be a C function, and want to extract my_list into
> an integer length and a double * pointing to the values. I spent some
> time searching through the extension guide in the docs, but either this
> isn't there or I missed the section in which it is discussed. I also
> flipped through a few of my python books without luck.
> 
> Could some kind soul take pity on me and tell me how to do this? Thanks
> in advance...
> 
> Rick

Here's some real code that's pretty close to what you want.  You can
use PyList_* instead of PySequence_* if speed is more important than
flexibility (PySequence works with any sequence object).
This example is a little different than what you requested (it's a
working python extension function).  But it does show how to iterate
a python list.

/////////////////////////
// syntax: obj = manifold([seq])
// returns: new manifold object
//
// Creates a manifold object, and initializes with sequence

static PyObject *module_manifold(PyObject *self, PyObject *args)
{
    PyObject *seq = NULL;
	if (!PyArg_ParseTuple(args, "|O", &seq)) return NULL;

	manifold__object *k = manifold__new();

    if (seq)
    {
        for (int i=0; i<PySequence_Length(seq); i++)
        {
            PyObject *obj = PySequence_GetItem(seq, i);
            manifold__insert_obj(k, k->root, obj);
        }
    }

    return (PyObject *)k;
}


What you want looks something like this (untested code):

double * my_function(PyObject *pylist, int *plength)
{
  double *array; 
  int i;
  *plength = PyList_Size(pylist);
  array = new double[*plength];

  for (i=0; i<*plength; i++)
  {
     array[i] = PyFloat_AsDouble(PyList_GetItem(pylist, i));
  }

  /* caller owns array */
  return array;
}






More information about the Python-list mailing list