Using C codes in Python | Set 1
Prerequisite: How to Call a C function in Python
Let’s discuss the problem of accessing C code from Python. As it is very evident that many of Python’s built-in libraries are written in C. So, to access C is a very important part of making Python talk to existing libraries. There is an extensive C programming API that Python provides but there are many different to deal with C.
Code #1 : [
work.c] C-Code that we are dealing.
Above code has different C-programming features.
divide() – returning multiple values, one through a pointer argument
avg() – performing a data reduction across a C array
Point and distance() – involve C structures.
Let’s assume that the code above is found in a file named work.c and it has been compiled into a library libsample that can be linked to other C code. Now, we have a number of C functions that have been compiled into a shared library. So, we call the functions entirely from Python without having to write additional C code or using a third-party extension tool.
Using ctypes :
Python ctypes will come to play but make sure the C code, that is to be converted, has been compiled into a shared library that is compatible with the Python interpreter (e.g., same architecture, word size, compiler, etc.).
Further the libsample.so file has been placed in the same directory as the
work.py. Let’s understand
Code #2 : Python module that wraps around resulting library to access it
Code #3 : Accessing code
Now, one can easily load the module and use the resulting C functions. See the next part – Using C codes in Python | Set 2.