Book Image

IPython Interactive Computing and Visualization Cookbook

By : Cyrille Rossant
Book Image

IPython Interactive Computing and Visualization Cookbook

By: Cyrille Rossant

Overview of this book

Table of Contents (22 chapters)
IPython Interactive Computing and Visualization Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 an os.system command, but this method does not extend to compiled libraries (on Windows, Dynamically Linked Libraries, or DLLs). 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 the 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 of this...