access to python function from C code

V

Vin

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

For example if I have defined
.... 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 ...
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
 
A

Alex Martelli

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

For example if I have defined

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top