The Wayback Machine - https://web.archive.org/web/20250115154303/https://www.geeksforgeeks.org/how-to-call-a-c-function-in-python/
Open In App

How to Call a C function in Python

Last Updated : 01 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.
First, let’s write one simple function using C and generate a shared library of the file. Let’s say file name is function.c. 

C




int myFunction(int num)
{
    if (num == 0)
 
        // if number is 0, do not perform any operation.
        return 0;
    else
        // if number is power of 2, return 1 else return 0
          return ((num & (num - 1)) == 0 ? 1 : 0) ;
 
}


Compile this : 

cc -fPIC -shared -o libfun.so function.c

Using ctypes(foreign function interface) library to call C function from Python

The above statement will generate a shared library with the name libfun.so. Now, let’s see how to make use of it in python. In python, we have one library called ctypes. Using this library we can use C function in python. 
Let’s say file name is function.py. 
 

Python3




import ctypes
NUM = 16     
# libfun loaded to the python file
# using fun.myFunction(),
# C function can be accessed
# but type of argument is the problem.
                        
fun = ctypes.CDLL("libfun.so") # Or full path to file 
# Now whenever argument
# will be passed to the function                                                       
# ctypes will check it.
           
fun.myFunction.argtypes = [ctypes.c_int]
 
# now we can call this
# function using instant (fun)
# returnValue is the value
# return by function written in C
# code
returnVale = fun.myFunction(NUM)       



Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg