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
- Important differences between Python 2.x and Python 3.x with examples
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Sort Python Dictionaries by Key or Value
- Python | Set 4 (Dictionary, Keywords in Python)
- SQL using Python | Set 1
- max() and min() in Python
- zip() in Python
- gcd() in Python
- Python vs PHP
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.