Python C Extensions
Do Not Reinvent The Wheel.
Reuse Rich C Libraries Using Python C Extensions.
There are multiple ways and tools to provide Python C extensions. Here are some of them.
• Python/C API
We will explore ctypes module.
Steps for 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
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
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-
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.
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.
Data Structures in Python