calling Python from C: I can't get this part.

Very Frustrated rwadkins at flash.net
Fri Dec 10 12:56:25 EST 1999


I know this should be easy, but I've read the documents at www.python.org
and the SWIG manual and it is still not clear how I do the following.
Maybe someone here can help.

I've used SWIG to port Arthur Corcoran's genetic algorithm library
(libga100) to Python.  It works fine with the example evaluation function
included in the library.  I've made all the helper functions within SWIG
to set and get values in genes, chromosomes, etc.

Here's the part I can't get.  Within the library, there's a structure
called the GA_Info_Ptr.  This structure keeps up with various things
about the GA run.  One item that it keeps up with is a pointer to the
evaluation function that is called to score a chromosome.  In C, this
looks like the following (abbreviated) code:

typedef struct {
	/* much stuff and */
	FN_Ptr	EV_fun; /* a pointer to the function to be called */
	/* more stuff */
} *GA_Info_Ptr

Before the GA can be run, the EV_fun pointer has to be set by a call to a
configuration function:

GA_Info_Ptr GA_config((*EV_fun)()) {
	GA_Info_Ptr ga_info;
	ga_info = CF_alloc(); /* this initializes a GA_Info_Ptr structure */

	/* the function pointer in the structure is then set to that given*/
	/* in the call to GA_config()	*/

     ga_info->EV_fun = EV_fun;
	return ga_info;
}

You would then call it like this in main() somewhere:

/* define your evaluation function */

int obj_fun(Chrom_Ptr chrom) {
	/* do some stuff with chrom */
	return;
}

/* then call the configuration routine */
GA_config(obj_fun);


Now, all I want to do is, instead of pointing to a C function that has to
be compiled and included in the library, I want to have ga_info->EV_fun
point to a Python function and have the Python function receive the
(Chrom_Ptr chrom) argument.

The rest is easy, but even after looking at the examples in the SWIG
manual, I am still not clear how you do this.

Any help would be greatly appreciated.

--Randy





Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list