Python Program to Invoke C Code

Python provides a feature to call C functions in python program.

There are three methods available in python to use C code in python program.

  • ctypes
  • SWIG
  • Python/C API

There are few advantages when calling c functions in python program for some situations.

  • Suppose some legacy functions written in C code which need to be called in python code.
  • C code is faster than python code, so certain functions you may need to write in c code.
  • C code is better for accessing or reading low level resources.

ctypes module to call C functions in python program

ctypes module provides C compatible data types and functions to load DLLs.
C function: Create c program as example.c file.
#include                                                               
int mul(int a, int b)                                                           
{                                                                               
  return a*b;                                                                   
}     

Create a DLL for above C function using command

gcc -shared -Wl,-soname,example -o example.so -fPIC example.c

This above command compiles example.c and generates .so DLL 'example.so' which can be used in python program.

Calling C DLL function in python program

from ctypes import *                                                            
                                                                                
#loading DLL file                                                               
example = CDLL('../cprog/example.so')                                           
                                                                                
#Finds multiplication of two integers                                           
result = example.mul(20,5)                                                      
print("Multiplication of 20 and 5 = %d" % result)   
Output:
Multiplication of 20 and 5 = 100

SWIG - Simplified Wrapper and Interface Generator

This is another way to include C code in python program. Please refer this approach in SWIG Website.

Python / C API

This python/ C API method is most widely used method which supports to manipulate python objects in your C code.
All objects in python are denoted as a PyObject struct and the Python.h header file has various functions for manipulation.
PyList_Size() function on the struct is used to get ength of list or array.
python / c api can be referred in website.

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^