If you are unsure whether it can be possible to call a C function in Python, follow this article’s guidelines for further help.
Call a C Function in Python
Calling a C function in Python is a matter of simple steps discussed below:
Step 1: First, create a C file on any system. I am creating the file on a Linux system using the following command:
Step 2: Inside the file, add the following function.
{
if (numb == 0)
// Do not perform any operation if number is 0.
return 0;
else
// Return 1 else return 0 if number is power of 2
return ((numb & (numb - 1)) == 0 ? 1 : 0) ;
}
Note: You can add any C function you want inside the file.
Step 3: Now, you must generate a shared library “libfun.so” of the file using the following command:
This generates the “libfun.so” shared library on the system.
ctypes is a Python library that allows users to call a C function inside a Python program. To use this library, the users must import it at the start of the Python program.
Step 4: Let’s create a Python file using nano editor in Linux from the following command:
Step 5: Inside the file, add the following code:
Num= 16
# libfun loads the python file
# via fun.mycode(),
# Access the C function
fun = ctypes.CDLL("location of libfun.so") # Or full path to file
# ctypes will check it whenever an argument is passed
fun.mycode.argtypes = [ctypes.c_int]
# Call the function using instant (fun)
# return the value by function in C
# code
returnVale = fun.mycode(Num)
Note: Ensure replacing “mycode()” with your function name and the location of libfun.so file.
Step 6: Save the file using “CTRL+X”, add “Y” and enter to exit.
Step 7: Execute the Python code to confirm its successful compilation on the system.
In this way, you can call a C function in Python on any system by following the above-given steps.
Conclusion
Calling a C function inside the Python program can be done easily by first creating a C function inside a file with a .c extension. Then compile the file to generate a shared library after that, import “ctypes” library in a Python program and use the shared library inside the code to call a function in Python on any system.