Last Updated : 11 Jul, 2025
Prerequisite:
Using C codes in Python | Set 1In 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 Python3 1==
import work
print ("GCD : ", work.gcd(35, 42))
print ("\ndivide : ", work.divide(42, 8))
print ("\navg : ", work.avg([1, 2, 3]))
p1 = work.Point(1, 2)
p2 = work.Point(4, 5)
print ("\ndistance : ", work.distance(p1, p2))
Output :
GCD : 7 divide : (5, 2) avg : 2.0 distance : 4.242640687119285Issue ?
Now the work done above has an issue that for the overall packaging of C and Python code together, using
ctypesto 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 Python3 1==
from ctypes.util import find_library
find_library('m')
find_library('pthread')
find_library('sample')
Output :
/usr/lib/libm.dylib /usr/lib/libpthread.dylib /usr/local/lib/libsample.so
Again,
ctypeswon’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.
Python3 1==
_mod = ctypes.cdll.LoadLibrary(_path)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4