> Articles > Python C Extensions

Python C Extensions

Python C Extensions provides the ability to use C code with Python.

Do Not Reinvent The Wheel.
Reuse Rich C Libraries Using Python C Extensions.

There are multiple ways and tools to provide Python C extensions to use C code with python. Here are some of them.

  • ctypes

  • Python/C API

  • SWIG

  • Cython

  • pyrex

  • SIP

  • Boost.Python

We will explore ctypes module.

Steps for Python C Extensions (ctypes)

Here are the steps for doing Python C Extensions-

Step 1 – Write a C source file having function to be used by python program.

Step 2 – Write a Python Program to use C function available in C source file.

Step 3 – Create shared object from C source file using gcc compiler

Step 4 – Execute Python program to use C function.


C source file - tools.c

Python C Extensions - C source file

So we have function SumOfDigits in C source file. It takes a number as parameter and returns the sum of digits of that number. We will be using this function in Python file.

Python source file - testtools.py

Python C Extensions - Python source file

We are importing ctypes module and in the next statement we are loading the shared object file tools.so. We will be creating tools.so from C source file tools.c. We are calling the function SumOfDigits and we are passing variable num as parameter.

Now we will create the shared library tools.so-

Python C Extensions - Creation of shared file

I am using GNUstep environment and MinGW32. You can use any Linux system. We are using the option - -share, -fPIC for creating share object. The same will be applicable on any other Linux system.

Now we will execute python program which uses C function SumOfDigits available in shared library tools.so.

Python C Extensions - Execution of program

Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth", "Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of multiple products. This article is from his course on Advanced Python.