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

(yzsuai) #1

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


Python calls a C extension module


to register handlers, trigger events


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


import cregister


print('\nTest1:')
cregister.setHandler(callback1) # register callback function
for i in range(3):
cregister.triggerEvent() # simulate events caught by C layer


print('\nTest2:')
cregister.setHandler(callback2)
for i in range(3):
cregister.triggerEvent() # routes these events to callback2


That’s it—the Python/C callback integration is set to go. To kick off the system, run
the Python script; it registers one handler function, forces three events to be triggered,
and then changes the event handler and does it again:


.../PP4E/Integrate/Embed/Regist$ make -f makefile.regist
gcc cregister.c -g -I/usr/local/include/python3.1 -shared -L/usr/local/bin
-lpython3.1 -o cregister.dll

.../PP4E/Integrate/Embed/Regist$ python register.py

Test1:
callback1 => spam number 0
callback1 => spam number 1
callback1 => spam number 2

Test2:
callback2 => spamspamspam
callback2 => spamspamspamspam
callback2 => spamspamspamspamspam

This output is printed by the C event router function, but its content is the return values
of the handler functions in the Python module. Actually, something pretty wild is going
on under the hood. When Python forces an event to trigger, control flows between
languages like this:



  1. From Python to the C event router function

  2. From the C event router function to the Python handler function

  3. Back to the C event router function (where the output is printed)

  4. And finally back to the Python script


That is, we jump from Python to C to Python and back again. Along the way, control
passes through both extending and embedding interfaces. When the Python callback
handler is running, two Python levels are active, and one C level in the middle. Luckily,
this just works; Python’s API is reentrant, so you don’t need to be concerned about


1534 | Chapter 20: Python/C Integration

Free download pdf