access to python function from C code

Vin fractal97 at hotmail.com
Thu Nov 13 11:36:29 EST 2003


Is it possible to access a function defined in python shell from c-code?

For example if I have defined

>>> def c(x):
...  return x*x
...

and defined in some module foo

static PyObject *
ptk_doit(PyObject *self, PyObject *args)
{

    get reference to a function here from python interpreter and apply the
function to a given value ...

   return Py_BuildValue("d",result);
}


then I can do ...

>>> import foo
>>>foo.doit(c,4)
16

Stuff like this can be done in C when one just transfers the pointer to a
function through input arguments
but then the transfered functions are always set at the time of compilation.
It would be useful if the above can be done, then any function can be
supplied to an underlying C code
without compilation.  Probably the performance would be affected but that my
not be a problem in some cases.

Needs like this arise in Optimization for example when
objective function can be arbitrary and optimization is done with general
optimization routines written in C.

Vin




More information about the Python-list mailing list