ctypes: Calling C Libraries from Python
Load shared libraries and call C functions using ctypes.
What Is ctypes?
ctypes is a standard-library module for loading shared C libraries and calling their functions from Python — no compilation required.
import ctypes
# Load the C standard library
libc = ctypes.CDLL("libc.so.6") # Linux
# libc = ctypes.CDLL("libSystem.dylib") # macOS
libc.puts(b"Hello from C!")Loading Libraries
Use ctypes.CDLL for cdecl calling convention (most C libraries) and WinDLL for Windows stdcall APIs.
import ctypes
# Platform-independent approach:
import ctypes.util
libm_name = ctypes.util.find_library("m")
libm = ctypes.CDLL(libm_name)
result = libm.sqrt
result.restype = ctypes.c_double
result.argtypes = [ctypes.c_double]
print(result(2.0)) # 1.4142...All lessons in this course
- Why C Extensions? Use Cases and Trade-offs
- ctypes: Calling C Libraries from Python
- cffi: C Foreign Function Interface
- Writing a Python C Extension Module