Back
+15 XP
Concept

Calling C Libraries with ctypes

The standard `ctypes` library provides C-compatible data types and loads shared C dynamic libraries (`.so`, `.dll`), invoking native C functions with zero build steps 🦾.

python
import ctypes

# Access standard C runtime library:
libc = ctypes.CDLL(None)

# Call C standard library abs():
c_abs = libc.abs
c_abs.argtypes = [ctypes.c_int]
c_abs.restype = ctypes.c_int

print(f"C libc.abs(-42) = {c_abs(-42)} 🦾")

# 86. Calling C Libraries with ctypes The standard `ctypes` library provides C-compatible data types and loads shared C dynamic libraries (`.so`, `.dll`), invoking native C functions with zero build steps 🦾. ```python import ctypes # Access standard C runtime library: libc = ctypes.CDLL(None) # Call C standard library abs(): c_abs = libc.abs c_abs.argtypes = [ctypes.c_int] c_abs.restype = ctypes.c_int print(f"C libc.abs(-42) = {c_abs(-42)} 🦾") ``` Always explicitly define `.argtypes` and `.restype` on C functions. Passing mismatched bit-widths directly corrupts C stack frames and causes segfaults! 🦾 --- ### Question Why should you always define `func.argtypes` and `func.restype` when using `ctypes`? 🧠 - [ ] a. To prevent data corruption, bad pointer casts, and segmentation faults across language boundaries 🦾 - [ ] b. To tell CPython to compile the code into JavaScript - [ ] c. Because Python functions cannot return integers without restype - [ ] d. To register the C function in the Linux kernel namespace --- ### Challenge Import `ctypes`. Load standard C library with `libc = ctypes.CDLL(None)`. Configure `libc.abs` with `argtypes = [ctypes.c_int]` and `restype = ctypes.c_int`. Print `libc.abs(-99)`. 🎯 <details> <summary>Solution</summary> ```python import ctypes libc = ctypes.CDLL(None) libc.abs.argtypes = [ctypes.c_int] libc.abs.restype = ctypes.c_int print(libc.abs(-99)) ``` </details>

Checkpoint

Why should you always define `func.argtypes` and `func.restype` when using `ctypes`? 🧠

Practice

Import `ctypes`. Load standard C library with `libc = ctypes.CDLL(None)`. Configure `libc.abs` with `argtypes = [ctypes.c_int]` and `restype = ctypes.c_int`. Print `libc.abs(-99)`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks