Table of Contents
We can call a C function from Python program using the ctypes module.
Calling C Function from Python
It involves the following steps:
- Creating a C file (.c extension) with the required functions
- Creating a shared library file (.so extension) using the C compiler.
- In the Python program, create a ctypes.CDLL instance from the shared file.
- Finally, call the C function using the format
{CDLL_instance}.{function_name}({function_parameters}).
Step 1: Creating a C File with some functions
#include <stdio.h>
int square(int i) {
return i * i;
}
We have a simple C function that will return the square of an integer. I have saved this function code in the file named my_functions.c.
Step 2: Creating the Shared Library File
We can use the following command to create the shared library file from the C source file.
$ cc -fPIC -shared -o my_functions.so my_functions.c
Step 3: Calling C Function from Python Program
>>> from ctypes import *
>>> so_file = "/Users/pankaj/my_functions.so"
>>> my_functions = CDLL(so_file)
>>>
>>> print(type(my_functions))
<class 'ctypes.CDLL'>
>>>
>>> print(my_functions.square(10))
100
>>> print(my_functions.square(8))
64
>>>
If you change the C program file, you will have to regenerate the shared library file.
Conclusion
The python default implementation is written in C programming and it's called CPython. So it's not very uncommon to use C functions in a python program. In this tutorial, we learned how to easily call C functions in a python program.