Unpacking a python list in C?

George Demmy gdemmy at layton-graphics.com
Thu May 2 13:30:40 EDT 2002


"Richard P. Muller" <rpm at wag.caltech.edu> writes:

> 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
> -- 
> Richard P. Muller, Ph.D. 
> rpm at wag.caltech.edu 
> http://www.wag.caltech.edu/home/rpm

I was just thrashing around with something similar...

foomodule.c:

#include "Python.h"

/* Return product of three numbers in a list or tuple */

static PyObject *
foo_bar(PyObject *self, PyObject *args)
{
  double x,y,z;
  
  if (!PyArg_ParseTuple(args, "(ddd)", &x, &y, &z))
    return NULL;

  return Py_BuildValue("d", x * y * z);
}


static PyMethodDef foo_methods[] = {
  { "bar", foo_bar, METH_VARARGS, "bar" },
  { NULL, NULL, 0, NULL }
};

void
initfoo(void)
{
  (void) Py_InitModule("foo", foo_methods);
}


compile shared object (Makefile notation):
CC = gcc
INC = -I/usr/local/src/Python-2.2/Include/ -I/usr/local/src/Python-2.2/
OPTS = -shared -Xlinker -export-dynamic -fPIC 

$(CC) $(INC) $(OPTS) -o foomodule.so foomodule.o

Python (foo module in current dir or otherwise in PYTHONPATH):

> import foo
> foo.([1,2,3])
6.0
>

Sources for the whys and wherefores of the above

http://www.python.org/doc/
Extending and Embedding the Python Interpreter, Rel 2.2.1 GvR and FLD, Jr.
Python/C API Reference Manual, Rel 2.2.1 GvR and FLD, Jr.

This example is limited to tuples and lists containing exactly 3 numbers
elements. However, it is a working example and should be enough to get
you playing around with something.

G




More information about the Python-list mailing list