How to call a C function in Python

First, let`s write one simple function using C and generate a shared library file. Let`s say the file name is — function.c.

int myFunction ( int num)


if (num == 0)


// if the number is 0, do not perform any operations.

return 0; 


  // if the number is a power of 2, return 1, otherwise return 0


num & amp; (num - 1) == 0?  return 1: return 0


Compile this:

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

Usage ctypes (external function interface) libraries for calling a C function from Python

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

import ctypes

NUM = 16  
# libfun loaded into python file
# using fun.myFunction (),
# C function can be accessed
# but the type of the argument is a problem.


fun = ctype.CDLL (libfun.so) 

# Now whenever an argument
# will be passed to the function
# ctypes will check this.

fun.myF unction.argtypes (ctypes.c_int)

# now we can call it
# function using instant (fun)
# returnValue this value
# return by function written in C
# code

returnVale = fun.myFunction (NUM) 

Get Solution for free from DataCamp guru