How to Call a C function in Python

Have you ever came across the situation where you have to call C function using python? This article is going to help you on 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 shared library of the file. Let’s say file name is function.c.

filter_none

edit
close

play_arrow

link
brightness_4
code

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
          
    num & (num - 1) == 0 ? return 1 : return 0
}

chevron_right


Compile this :



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

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

Above statement will generate a shared library with 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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 = ctype.CDLL(libfun.so)  
# 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)        

chevron_right




My Personal Notes arrow_drop_up

Embedded software Engineer at Agiledge Process Solutions currently working on python Development

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : srishti verma



Article Tags :

3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.