CoursesGalaxy Courses Subscription Knowledge Hub
Knowledge Hub
Design Patterns

Python C Extension

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.

Enroll Now and Get an Early Bird Offer

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

C Code In Python - 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 -

C Code In Python - Python source file

We are importing ctypes module and in the next statement we are loading the shared object file We will be creating 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

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

Python C Extensions - Execution of program

Suresh Kumar Srivastava is founder of online learning site 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.

Yearly Subscription

Advanced Python

Data Structures in Python




Knowledge Hub

Design Patterns

Tech Articles

About Us


Contact Us


CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap between education and industry and provide the training on specific problems of industry to enhance the skills of Engineers in industry to do their job appropriately.

Learn From Us

2018 CourseGalaxy