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.
- Using C codes in Python | Set 2
- Reading and Generating QR codes in Python using QRtools
- Python | Convert list to Python array
- Important differences between Python 2.x and Python 3.x with examples
- Python | Index of Non-Zero elements in Python list
- Reading Python File-Like Objects from C | Python
- Python | Merge Python key values to list
- Python | Add Logging to Python Libraries
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- Python | Visualizing O(n) using Python
- SQL using Python | Set 1
- pow() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.