Calling python from a C function that is embedded in python?

Greg Ewing (using news.cis.dfn.de) ckea25d02 at sneakemail.com
Tue Apr 8 01:18:55 EDT 2003


Greg Ewing (using news.cis.dfn.de) wrote:
 > VanL wrote:
 >> I want python to be able to call wrapped functions like
 >> they are python functions, and a wrapped C library to call wrapped
 >> python functions like they were in C.
 >
 > I have a demo showing how to do it with Pyrex, but I don't have it
 > here right now.

Well, I found the demo. It shows how you can pass a
Python function to a C library as a callback.

cheesefinder.h:
-------------------------------------------------------
typedef void (*user_func)(char *name, void *user_data);
void find_cheeses(user_func f, void *user_data);
-------------------------------------------------------

cheesefinder.c:
-------------------------------------------------------
#include "cheesefinder.h"

static char *cheese_list[] = {
   "cheddar",
   "camembert",
   "that runny one",
};

void find_cheeses(user_func f, void *user_data) {
   char **p = cheese_list;
   while (*p) {
     f(*p, user_data);
     ++p;
   }
}
-------------------------------------------------------

cheese.pyx:
-------------------------------------------------------
cdef extern from "cheesefinder.h":
   ctypedef void (*user_func)(char *name, void *user_data)
   void find_cheeses(user_func f, void *user_data)

def find(f):
   find_cheeses(callback, <void*>f)

cdef void callback(char *name, void *f):
   (<object>f)(name)
-------------------------------------------------------

run_cheese.py:
-------------------------------------------------------
import cheese

def report_cheese(name):
   print "Found cheese:", name

cheese.find(report_cheese)
-------------------------------------------------------

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list