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

(yzsuai) #1

function object directly and printing its return value that is sent back to C. Input to the
transform function is a function argument here, not a preset global variable. Notice
that message is fetched as a module attribute this time, instead of by running its name
as a code string; as this shows, there is often more than one way to accomplish the same
goals with different API calls.


Running functions in modules like this is a simple way to structure embedding; code
in the module file can be changed arbitrarily without having to recompile the C program
that runs it. It also provides a direct communication model: inputs and outputs to
Python code can take the form of function arguments and return values.


Running Strings in Dictionaries


When we used PyRun_String earlier to run expressions with results, code was executed
in the namespace of an existing Python module. Sometimes, though, it’s more con-
venient to create a brand-new namespace for running code strings that is independent
of any existing module files. The C file in Example 20-28 shows how; the new name-
space is created as a new Python dictionary object, and a handful of new API calls are
employed in the process:


PyDict_New
Makes a new empty dictionary object


PyDict_SetItemString
Assigns to a dictionary’s key


PyDict_GetItemString
Fetches (indexes) a dictionary value by key


PyRun_String
Runs a code string in namespaces, as before


PyEval_GetBuiltins
Gets the built-in scope’s module


The main trick here is the new dictionary. Inputs and outputs for the embedded code
strings are mapped to this dictionary by passing it as the code’s namespace dictionaries
in the PyRun_String call. The net effect is that the C program in Example 20-28 works
just like this Python code:


>>> d = {}
>>> d['Y'] = 2
>>> exec('X = 99', d, d)
>>> exec('X = X + Y', d, d)
>>> print(d['X'])
101

But here, each Python operation is replaced by a C API call.


1526 | Chapter 20: Python/C Integration

Free download pdf