Wrapping a C library in Python with ctypes
Wrapping a C library in Python allows us to leverage existing C code or to implement a critical part of the code in a fast language such as C.
It is relatively easy to use externally-compiled libraries with Python. The first possibility is to call a command-line executable with the os.system()
command, but this method does not extend to compiled libraries.
A more powerful method consists of using a native Python module called ctypes. This module allows us to call functions defined in a compiled library (written in C) from Python. The ctypes module takes care of data type conversions between C and Python. In addition, the numpy.ctypeslib
module provides facilities to use NumPy arrays wherever data buffers are used in the external library.
In this example, we will rewrite the code of the Mandelbrot fractal in C, compile it in a shared library, and call it from Python.
Getting ready
The code in this recipe is written for Unix systems and has been tested...