3.2 Calling Python Callables from C

So far we have concentrated on making C functions callable from Python. The reverse is also useful: calling Python functions from C. In fact, as in Python, as far as the C API is concerned Python functions are just a particular case of a callable type: you don't have to care whether it's a Python function, bound method, builtin function, type object, instance of a user-defined type that has a __call__ method or whatever else.

In some sense, the primitive API function for all this - the function that all the other functions that will be described in this section end up calling - is PyObject_Call. This function takes three arguments:

  1. func: the object you wish to call.
  2. args: a tuple of positional arguments.
  3. kw: a dictionary containing keyword arguments, or NULL if none are to be passed.

So a call ``PyObject_Call(func, t, kw)'' is essentially the same as ``func(*t, **kw)'' in Python - except the former does no error checking on t or kw. Get it wrong and a segfault or access violation is likely to be the result.

For this reason it is often preferable to use the API function ``PyEval_CallObjectWithKeywords'' which has the same signature as PyObject_Call but does do error checking on its arguments. As with essentially all API functions, both PyObject_Call and PyEval_CallObjectWithKeywords return NULL on failure with an exception set. If they succeed they transfer ownership of the resulting reference back to the caller (as the result is fairly likely to be a new object, there's not really anything else that could be the case).

It's fairly rare that you will want to supply keyword arguments, so there is a convenience macro:

#define PyEval_CallObject(func,arg) \
        PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)

If you do not happen to have a tuple of arguments lying around, you can use PyEval_CallFunction:

PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj, char *format, ...);

The string format and the following arguments are as for Py_BuildValue (XXX so i really should have described that by now!). A call such as

PyEval_CallFunction(obj, "iii", a, b, c);

is equivalent to

PyEval_CallObject(obj, Py_BuildValue("iii", a, b, c));

but with error checking and not leaking the tuple of arguments...

Another convenience function is PyEval_CallMethod. Again, a call

PyEval_CallMethod(obj, "insert", "iO", i, item);

is, modulo error checking and getting the reference count details right, the same as

PyEval_CallObject(PyObject_GetAttrString(obj, "insert"), 
		  Py_BuildValue("iO", i, item));

XXX examples!

THIS DOCUMENT IS A DRAFT! Comments to mwh@python.net please.