[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Ultimately, this C file is an extension module for Python, not a standalone C program
that embeds Python (though C could just as well be on top). To compile it into a
dynamically loaded module file, run the makefile in Example 20-31 on Cygwin (and
use something similar on other platforms). As we learned earlier in this chapter, the
resulting cregister.dll file will be loaded when first imported by a Python script if it is
placed in a directory on Python’s module search path (e.g., in. or PYTHONPATH settings).


Example 20-31. PP4E\Integrate\Embed\Regist\makefile.regist


######################################################################


Cygwin makefile that builds cregister.dll. a dynamically loaded


C extension module (shareable), which is imported by register.py


######################################################################


PYLIB = /usr/local/bin
PYINC = /usr/local/include/python3.1


CMODS = cregister.dll


all: $(CMODS)


cregister.dll: cregister.c
gcc cregister.c -g -I$(PYINC) -shared -L$(PYLIB) -lpython3.1 -o $@


clean:
rm -f *.pyc $(CMODS)


Now that we have a C extension module set to register and dispatch Python handlers,
all we need are some Python handlers. The Python module shown in Example 20-32
defines two callback handler functions and imports the C extension module to register
handlers and trigger events.


Example 20-32. PP4E\Integrate\Embed\Regist\register.py


"""
#########################################################################
in Python, register for and handle event callbacks from the C language;
compile and link the C code, and launch this with 'python register.py'
#########################################################################
"""


####################################


C calls these Python functions;


handle an event, return a result


####################################


def callback1(label, count):
return 'callback1 => %s number %i' % (label, count)


def callback2(label, count):
return 'callback2 => ' + label * count


Registering Callback Handler Objects | 1533
Free download pdf