Prerequisite: Using C codes in Python | Set 1
In the previous article, we have discussed how to access C code in Python. Now, let’s see how to access C functions.
Code #1 : Accessing C functions with Python
GCD : 7 divide : (5, 2) avg : 2.0 distance : 4.242640687119285
Now the work done above has an issue that for the overall packaging of C and Python code together, using ctypes to access C code that has been compiled, one has to make sure that the shared library gets placed in a location, where the
work.py module can find it. One possibility is to put the resulting
libsample.so file in the same directory as the supporting Python code.
So, if the C library is installed elsewhere, then path has to be adjusted accordingly. If it is installed as a standard library on the machine, then
ctypes.util.find_library() function can be used.
Code #2 : Path Example
/usr/lib/libm.dylib /usr/lib/libpthread.dylib /usr/local/lib/libsample.so
Again, ctypes won’t work at all if it can’t locate the library with the C code.
ctypes.cdll.LoadLibrary() is used to load the C library, once it’s location is known.
- Using C codes in Python | Set 1
- 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 email@example.com. 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.