CHAPTER TWO CREATING EXTENSIONS WITHOUT THIRD PARTY TOOLS 2.1 Extending Python with C or C++ 2.1.1 A Simple Example 1 An interface for this function already exists in the standard module os — it was chosen as a simple and straightforward example. 5 This section of the guide covers creating C and C++ extensions without assistance from third party tools. It is intended primarily for creators of those tools, rather than being a recommended way to create your own C extensions. It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls. To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header$_{"Python.h"}$ . The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters. Note: The C extension interface is specific to CPython, and extension modules do not work on other Python implementations. In many cases, it is possible to avoid writing C extensions and preserve portability to other imple- mentations. For example, if your use case is calling C library functions or system calls, you should consider using the$_{ctypes}$module or the cffi library rather than writing custom C code. These modules let you write Python code to interface with C code and are more portable between implementations of Python than writing and compiling a C extension module. Let’s create an extension module called$_{spam}$(the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function$_{system()}$ $^{1}$. This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows: Begin by creating a file$_{spammodule.c}$ . (Historically, if a module is called$_{spam}$, the C file containing its imple- mentation is called$_{spammodule.c}$ ; if the module name is very long, like$_{spammify}$, the module name can be just$_{spammify.c}$ .) The first two lines of our file can be: >>> import spam >>> status=spam.system("ls -l ") #define PY_SSIZE_T_CLEAN #include<Python.h>