Callbacks/function pointers.

Michael P. Reilly arcege at shore.net
Mon May 24 13:45:01 EDT 1999


Jr. King <n at n.com> wrote:
: I don't know how to ask this question, so let me tell you what I want.  I
: want to be able to use c/c++ to call user defined functions in python
: dynamically, like function pointers in c/c++.

: python user sets the function, c/c++ saves the function*, when appropriate
: c/c++ calls the python function.

: Is it possible, if so could you show a small example showing both the c/c++
: and python side.
: Thanx

Surely, it's possible. :)

Functions (and methods) are first-class objects, meaning they can be
passed around as entities (like pointers to functions in C).  Then you
can use the Python C API to call the function with the appropriate
arguments.

  PyObject *python_callback(func, args)
    PyObject *func, *args;
    { PyObject *res, *tmp_args;

      /* check arguments, raise exceptions if appropriate */
      if (!PyCallable_Check(func)) {
        PyErr_SetString(PyExc_TypeError, "function not callable");
        return NULL;
      }
      /* if the argument is not a tuple, put it inside a tuple */
      if (PyTuple_Check(args)) {
        tmp_args = args;
      else {
        if ((tmp_args = PyTuple_New(1)) == NULL)
          return NULL;
        PyTuple_SetItem(tmp_args, 0, args);
      }
      res = PyObject_CallObject(func, tmp_args);
      if (tmp_args != args)
        Py_DECREF(tmp_args);
      return res;
    }

If you want to pass C objects, then you can use:
  char *name;
  int age;
  res = PyObject_CallFunction(func, "si", name, age);

Have a look at the "Extending and Embedding" and "Python/C API" docs at
http://www.python.org/doc/.

  -Arcege





More information about the Python-list mailing list