Linux/Unix > Python Essential Reference, Second Edition > B. Extending and Embedding Python > Calling Python from C | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105095080116218138201087

### Calling Python from C

Sometimes it’s useful to call Python functions from C programs. To do this, the following functions can be used:

    PyObject *PyEval_CallObject(PyObject *func, PyObject *args)

Call `func` with arguments `args` . `func` is a Python callable object (function, method, class, and so on). `args` is a tuple of arguments.

    PyObject *PyEval_CallObjectWithKeywords(PyObject *func, PyObject *args, PyObject *kwargs)

Call `func` with positional arguments `args` and keyword arguments `kwargs` . `func` is a callable object, `args` is a tuple, and `kwargs` is a dictionary.

The following example illustrates the use of these functions:

    /* Call a python function */

    PyObject *func;    /* Callable object. */
    PyObject *args;
    PyObject *result;
    int       arg1, arg2;

    func = get_python_function()  /* See below */
    args = Py_BuildValue("(ii)", arg1, arg2);  /* Build argument list */
    result = PyEval_CallObject(func,args);     /* Call function       */

The only remaining problem is that C code, at compile time, cannot know the address of a Python object that has not yet been created, since Python is dynamic. One approach is to let Python create the function object and then register the address with a callback function. To deal with this, extension code such as the following can be used to set the callback function:

    static PyObject *func = 0;    /* Callback function */

    static PyObject *
    set_callback(PyObject *self, PyObject *args) {
         PyObject *f;
         if (PyArg_ParseTuple(args,"O",&f)) {
            if (!PyCallable_Check(f)) {
               PyErr_SetString(PyExc_TypeError, "expected a callable");
               return NULL;
            }
           Py_XINCREF(f);        /* Save reference to callback */
           Py_XDECREF(func);     /* Release any previous callback */
           func = f;
           Py_INCREF(Py_None);
           return Py_None;
        }
        return NULL;
    }

This function would then be invoked from the interpreter as follows:

    # Some function
    def foo(x,y):
    return x+y
    ...
    set_callback(foo)

Alternatively, it might be possible to obtain Python callable objects using functions in the embedding API, described later in this appendix.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.