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

Very Frustrated rwadkins at flash.net
Tue Dec 14 17:40:41 EST 1999


Okay, almost there.  This is adapted from callback2 in the SWIG examples.

Here's a reminder: SWIG keeps up with pointers as strings.  For example,
if you have a function like:

*void myfunc(void) {
	int *p = NULL;
	return p;
}

using SWIG, from Python you would write:

>>>pointer = myfunc()
>>>print pointer
_0_void_p

or something to that effect.

This is causing some problems for me because my python functions need
this string value to work properly using the getattr and setattr helper
functions.

Here's where I am now:

/* set up the python callback evaluation */
static PyObject *my_pycallback = NULL;
static int PythonCallBack(Chrom_Ptr *chrom)
{
   PyObject *func, *arglist;
   PyObject *result;

   func = my_pycallback;	 /* This is the function .... */

/* the following almost works, but not quite */

   arglist = Py_BuildValue("s", chrom); /* the chrom pointer as string?*/
   result =  PyEval_CallObject(func, arglist);
   Py_DECREF(arglist);
   Py_XDECREF(result);
   return /*void*/;
}

/*Here's a helper function to call from Python to set the callback */
/* This part works okay, inasmuch as I get a pointer returned */

GA_Info_Ptr
GA_py_config(char *cfg_name, PyObject *PyFunc)
{
	GA_Info_Ptr ga_info; /* the GA_config returns a pointer */

	Py_XDECREF(my_pycallback);	      /* Dispose of previous callback */
	Py_XINCREF(PyFunc);		/* Add a reference to new callback */
	my_pycallback = PyFunc;			/* Remember new callback */

	ga_info = GA_config(cfg_name,PythonCallBack);
	return ga_info;
}

Now, here's the Python version of the C evaluation function.  It takes a
Chrom_Ptr argument (again, a string) and operates on it.  It works fine
as long as it's called from within Python.  The problem is that when it's
used as a callback, it doesn't work.  I believe this is due to alteration
to the Chrom_Ptr chrom argument when the function is called with :

   arglist = Py_BuildValue("s", chrom); /* the chrom pointer as string?*/
   result =  PyEval_CallObject(func, arglist);

Okay, here's the python function:

def func(chrom) :
# import all the GA functions
	from libga import *
	val = 0.0
	penalty = 1.0

# python will then exit the function while trying to execute the
# following statement

	fudge_factor = 1.0/(GA_chrom_length_get(chrom)*10.0)
	for i in range(GA_chrom_length_get(chrom)):
		if  (GA_chrom_gene_get(chrom,i)!= i+1):
			how_far_off = GA_chrom_gene_get(chrom,i)-(i+1)
			if how_far_off < 0:
				how_far_off = - how_far_off
			val = val + penalty + how_far_off*fudge_factor
	GA_chrom_fitness_set(chrom, val)
	return val

Any ideas how I get SWIG or Python to pass the Chrom_Ptr object to Python
as a string?

Thanks,
--Randy


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



More information about the Python-list mailing list