Create the C function:
First, create a file named add.c
with the following content:
// add.c
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
Compile the C function:
Next, you need to compile the C code into a shared library. If you’re on Linux or macOS, you can use gcc
:
gcc -shared -o libadd.so -fPIC add.c
On Windows, you might use gcc
from MinGW:
gcc -shared -o add.dll -Wl,--out-implib,libadd.a add.c
Call the C function from Python:
Create a Python script named call_add.py
with the following content:
import ctypes
# Load the shared library into ctypes
if __name__ == "__main__":
lib = ctypes.CDLL('./libadd.so') # Use 'add.dll' on Windows
# Define the argument and return types of the C function
lib.add.argtypes = [ctypes.c_int, ctypes.c_int]
lib.add.restype = ctypes.c_int
# Call the C function
result = lib.add(3, 5)
print(f'The result of adding 3 and 5 is: {result}')