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 make use of the simple Python module file shown in Example 20-1.

Example 20-1. PP2E\Integrate\Embed\Basics\usermod.py

#########################################################
# C runs Python code in this module in embedded mode.
# Such a file can be changed without changing the C layer.
# There is just standard Python code (C does conversions).
# You can also run code in standard modules like string.
#########################################################

import string

message = 'The meaning of life...'

def transform(input):
    input = string.replace(input, 'life', 'Python')
    return string.upper(input)

If you know any Python at all, you know that this file defines a string and a function; the function returns whatever it is passed with string substitution and upper-case conversions applied. It’s easy to use from Python:

[mark@toy ~/.../PP2E/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 proper API use, it’s not much more difficult to use this module the same way in C.

Running Simple Code Strings

Perhaps the simplest ...

Get Programming Python, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.