- Code files can communicate with most of the same techniques as code strings;
when run as separate programs, files can also employ Inter-Process Communica-
tion (IPC) techniques.
Naturally, all embedded code forms can also communicate with C using general system-
level tools: files, sockets, pipes, and so on. These techniques are generally less direct
and slower, though. Here, we are still interested in in-process function call integration.
Basic Embedding Techniques
As you can probably tell from the preceding overview, there is much flexibility in the
embedding domain. To illustrate common embedding techniques in action, this section
presents a handful of short C programs that run Python code in one form or another.
Most of these examples will make use of the simple Python module file shown in
Example 20-22.
Example 20-22. PP4E\Integrate\Embed\Basics\usermod.py
"""
#############################################################
C code runs Python code in this module in embedded mode.
Such a file can be changed without changing the C layer.
This is just standard Python code (C handles conversions).
Must be on the Python module search path if imported by C.
C can also run code in standard library modules like string.
#############################################################
"""
message = 'The meaning of life...'
def transform(input):
input = input.replace('life', 'Python')
return input.upper()
If you know any Python at all, you probably know that this file defines a string and a
function; the function returns whatever it is passed with string substitution and up-
percase conversions applied. It’s easy to use from Python:
.../PP4E/Integrate/Embed/Basics$ python
>>> import usermod # import a module
>>> usermod.message # fetch a string
'The meaning of life...'
>>> usermod.transform(usermod.message) # call a function
'THE MEANING OF PYTHON...'
With a little Python API wizardry, it’s not much more difficult to use this module the
same way in C.
1518 | Chapter 20: Python/C Integration