[Q] How Can I call python function from C source?

Dave Kuhlman dkuhlman at rexx.com
Thu Jun 27 19:11:11 CEST 2002


Kim Chul Min wrote:

> Hello there,
> 
> I want to call python function from c source.
> 
> for example,
> 
> in file "main.c"
> --------------------------------------------------------------
> int main(void)
> {
> 
>     /** want to call python function add(a,b) that return a+b **/
> 
> }
> --------------------------------------------------------------
> 
> in the file "add.py"
> --------------------------------------------------------------
> def add(a,b):
>     return(a+b)
> --------------------------------------------------------------
> 
> Can I call any function that written by python from C source ?
> 
> If possible, can anyone show me simple example like above??
> 
> Plz,,, Help me....Thankx in advance...
> 
> Ciao,
> Farangan Xavio
> cmkim at shinbiro.com

Here is a simple example.

You will find the following especially helpful:

    http://www.python.org/doc/current/api/importing.html
    http://www.python.org/doc/current/api/object.html

/* =========================================== */

#include "Python.h"

int main(int argc, char ** argv)
{
    PyObject * module;
    PyObject * function;
    PyObject * result;
    long cresult;
    int arg1;
    int arg2;

    if (argc != 3)
    {
        printf("Usage: test1 <arg1> <arg2>\n");
        exit(-1);
    } /* if */

    arg1 = atoi(argv[1]);
    arg2 = atoi(argv[2]);

    Py_Initialize();
    module = PyImport_ImportModule("add");
    if (PyObject_HasAttrString(module, "add"))
    {
        function = PyObject_GetAttrString(module, "add");
        if (PyCallable_Check(function))
        {
            result = PyObject_CallFunction(function, "ii", arg1, arg2);
            cresult = PyLong_AsLong(result);
            printf("arg1: %d  arg2: %d  result: %d\n", arg1, arg2, cresult);
        }
        else
        {
            printf("Error -- attribute is not a function/method\n");
        } /* if */
    }
    else
    {
        printf("Error -- Module does not contain \"add\" function.\n");
    } /* if */
    Py_Exit(0);
} /* main */

/* =========================================== */



-- 
Dave Kuhlman
dkuhlman at rexx.com
http://www.rexx.com/~dkuhlman




More information about the Python-list mailing list