python · March 26, 2023 0

How to Call a C function in Python

Table of Content

To call a C function in Python , you can use the ctypes (foreign function library) module in Python. ctypes allows you to load shared libraries (i.e., .dll, .so, or .dylib files) that contain the C functions and call them directly from Python.

Here is an example of how to call a C function add_two_numbers that adds two integers in a shared library my_library.dll using ctypes:

from ctypes import cdll

# Load the shared library
libmy_library = cdll.LoadLibrary('./my_library.dll')

# Declare the argument and result types of the C function
libmy_library.add_two_numbers.argtypes = (ctypes.c_int, ctypes.c_int)
libmy_library.add_two_numbers.restype = ctypes.c_int

# Call the C function and print the result
result = libmy_library.add_two_numbers(3, 5)

In this example, we use the cdll function from ctypes to load a shared library my_library.dll that contains the add_two_numbers function. We then declare the argument and result types of the function using the argtypes and restype attributes. Finally, we call the C function and print the result.

Note that ctypes provides other functions to load shared libraries, such as windll for Windows DLLs and osx and libc for macOS and Linux system libraries, respectively.

%d bloggers like this: