Calling a C function from Python

Step1: Create a C library

Create file calculator.c and enter this code:

int add(int a, int b)
{
    return a + b;
}

Compile the file to a library with this command:

cc -fPIC -shared -o calculator.so calculator.c

A new file 'calculator.so' is created.

Step2: Create a Python script that uses the C library

Create file main.py and enter this code:

import ctypes
import os

file_name = "calculator.so"
calculator = ctypes.cdll.LoadLibrary(file_name)

add_func = calculator.add
add_func.argtypes = (ctypes.c_int, ctypes.c_int)
add_func.restype = ctypes.c_int

result = add_func(4, 5)
print(result)

Step3: Test the program

You folder should contain the following 3 files:

calculator.c
calculator.so
main.py

Use 'python main.py' to execute the script. The result of the addition should be shown:

9