access to python function from C code

Alex Martelli aleax at aleax.it
Thu Nov 13 13:01:21 EST 2003


Vin wrote:

> 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 ...

Yes, it can be done.  Exactly how depends on how you want to call this
C-coded function, see below.

> 
>    return Py_BuildValue("d",result);
> }
> 
> 
> then I can do ...
> 
>>>> import foo
>>>>foo.doit(c,4)
> 16

So you want to pass the function object and its single argument?  OK, BUT:

> 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.

...that's very unlikely to be a sensible tack because you'll call that
function so MANY times the (big) performance impact will hurt.

Still, whatever makes you happy (warning, untested code)...:

    PyObject *func, *arg, *resultobj, *floatresult;
    double result;

    if(!PyArg_ParseTuple(args, "OO", &func, &arg))
        return NULL;
    resultobj = PyObject_CallFunctionObjArgs(func, arg, NULL);
    if (!resultobj)
        return NULL;
    floatresult = PyNumber_Float(resultobj);
    Py_DECREF(resultobj);
    if (!floatresult)
        return NULL;
    result = PyFloat_AS_DOUBLE(floatresult);
    Py_DECREF(floatresult);

this should be an acceptable body for ptk_doit before its return
statement.


Alex





More information about the Python-list mailing list