DEV Community

boopalan
boopalan

Posted on

july 30

trying the FFI between the c and the python3

i am planning the do a very simple ffi for an simple c program

int add (int a, int b) {
   return a + b;
}
Enter fullscreen mode Exit fullscreen mode

now let we compile this simple program for the linux

gcc -shared -o libadd.so add.c
Enter fullscreen mode Exit fullscreen mode

using this.so file in python program


import ctypes
import os

if os.name == 'posix':  
    lib = ctypes.CDLL('./libadd.so')
else:  
    lib = ctypes.CDLL('./add.dll')

lib.add.argtypes = [ctypes.c_int, ctypes.c_int]  
lib.add.restype = ctypes.c_int              

result = lib.add(5, 7)
print(f"5 + 7 = {result}")


Enter fullscreen mode Exit fullscreen mode

Top comments (0)