extending and embedding. Its extending interface (widget objects) is used to register
Python callback handlers, which are later run with embedding interfaces in response to
GUI events. You can study tkinter’s implementation in the Python source distribution
for more details; its Tk library interface logic makes it a somewhat challenging read,
but the basic model it employs is straightforward.
Registration Implementation
This section’s C and Python files demonstrate the coding techniques used to implement
explicitly registered callback handlers. First, the C file in Example 20-30 implements
interfaces for registering Python handlers, as well as code to run those handlers in
response to later events:
Event router
The Route_Event function responds to an event by calling a Python function object
previously passed from Python to C.
Callback registration
The Register_Handler function saves a passed-in Python function object pointer
in a C global variable. Python scripts call Register_Handler through a simple
cregister C extension module created by this file.
Event trigger
To simulate real-world events, the Trigger_Event function can be called from
Python through the generated C module to trigger an event.
In other words, this example uses both the embedding and the extending interfaces
we’ve already met to register and invoke Python event handler code. Study Exam-
ple 20-30 for more on its operation.
Example 20-30. PP4E\Integrate\Embed\Regist\cregister.c
#include <Python.h>
#include <stdlib.h>
//
/ 1) code to route events to Python object /
/ note that we could run strings here instead /
//
static PyObject Handler = NULL; / keep Python object in C */
void Route_Event(char label, int count)
{
char cres;
PyObject args, pres;
/ call Python handler /
args = Py_BuildValue("(si)", label, count); / make arg-list /
pres = PyEval_CallObject(Handler, args); / apply: run a call /
Py_DECREF(args); / add error checks /
Registering Callback Handler Objects | 1531