Stack of C functions created from Python

David N. Welton dwelton at linuxcare.com
Tue Aug 17 19:56:12 CEST 1999


I don't really know what the point of this might be, but I thought it
was sort of an interesting bit of code.  I guess it might be useful if
you had to execute a lot of C code that you weren't quite sure about
at run time, and wanted to do it in one big bunch.

/* 
   stackexe.c, by David N. Welton <davidw at prosa.it>

   To compile for Linux:
   gcc -shared -Wl,-soname,stackexe.so -o stackexe.so stackexe.c  
   */

#include <python1.5/Python.h>

typedef struct node {
    int (* func)();
    struct node *next;
} node;

node *head;
node *cur;

static int pa()
{
    puts("a");
}

static int pb()
{
    puts("b");
}

static PyObject *addpa(PyObject *self, PyObject *args)
{
    cur->func = pa;
    cur->next = malloc(sizeof(node));
    cur = cur->next;
    cur->next = NULL;
    return Py_None;
}

static PyObject *addpb(PyObject *self, PyObject *args)
{
    cur->func = pb;
    cur->next = malloc(sizeof(node));
    cur = cur->next; 
    cur->next = NULL;   
    return Py_None;
}

static PyObject *run(PyObject *self, PyObject *args)
{
    cur = head;
    while(cur->next != NULL)
    {
	(*cur->func)();
	cur = cur->next;
    }
    return Py_None;
}

static PyObject *freestack(PyObject *self, PyObject *args)
{
    node *nxt;
    cur = head->next;
    while(cur->next != NULL)
    {
	nxt = cur->next;
	free(cur);
	cur = nxt;
    }
    head->next = NULL;
    return Py_None;
}

static struct PyMethodDef stackexemethods[] = {
    {"addpa", addpa, METH_VARARGS},
    {"addpb", addpb, METH_VARARGS},
    {"run", run, METH_VARARGS},
    {"free", freestack, METH_VARARGS},
    {NULL, NULL}
};

void initstackexe()
{
    Py_InitModule("stackexe", stackexemethods);
    head = malloc(sizeof(node));
    head->next = NULL;
    cur = head;
}

An 'args' field could be added to the node struct, so that you could
pass things to the C functions that way.

Ciao,
-- 
David N. Welton, Web Engineer, Linuxcare, Inc.
415.354.4878 x241 tel, 415.701.7457 fax
dwelton at linuxcare.com, http://www.linuxcare.com/
Linuxcare. At the center of Linux.




More information about the Python-list mailing list