[python-uk] Please help in calling python fucntion from 'c'

Duncan Booth python-uk@python.org
Wed, 04 Sep 2002 13:32:52 +0100


On 4 Sep 2002 at 13:21, Praveen Patil wrote:

>     /* Here I want to call python function(TestFunction). Please suggest
> me
> some solution*/
> 

First, you want to work out how you would call it from a Python 
module, split down into as simple steps as possible. This is actually a 
bit tricky as you are trying to call a function in your main script so you 
have to be careful when importing it.

The best way would probably be to pass the function as an argument 
to RECEIVE_FROM_IL_S, but if you don't want to do that you would 
call it like this:

    import __main__
    fn = __main__.TestFunction
    fn()

Converting that to C you get something like this (untested code):

   PyObject *main = PyImport_ImportModule('__main__');
   PyObject *fn = PyObject_GetAttrString(main, "TestFunction");
   PyObject *result = PyObject_CallFunction(fn, NULL);

   Py_DECREF(result);
   Py_DECREF(fn);
   Py_DECREF(main);

Don't forget the code to adjust reference counts: the code you posted 
returns Py_None without incrementing it first: you mustn't do that. 
Always take extreme care over the reference counts when calling C 
from Python or vice versa.
 -- 
Duncan Booth                                             duncan@dales.rmplc.co.uk
int month(char *p){return(124864/((p[0]+p[1]-
p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
http://dales.rmplc.co.uk/Duncan