Back
+20 XP
Concept

Foreign Function Interface with ctypes

Building C extensions requires compilation pipelines. The built-in `ctypes` library loads compiled dynamic shared objects (`.so`, `.dll`) and invokes exported C functions directly from pure Python code 🔗.

python
import ctypes
import ctypes.util

# Load standard C library:
libc = ctypes.CDLL(ctypes.util.find_library("c"))

# Define function signature (argtypes and restype):
libc.abs.argtypes = [ctypes.c_int]
libc.abs.restype = ctypes.c_int

result = libc.abs(-42)
print(f"libc abs(-42): {result} 🔗")

# 97. Foreign Function Interface with ctypes Building C extensions requires compilation pipelines. The built-in `ctypes` library loads compiled dynamic shared objects (`.so`, `.dll`) and invokes exported C functions directly from pure Python code 🔗. ```python import ctypes import ctypes.util # Load standard C library: libc = ctypes.CDLL(ctypes.util.find_library("c")) # Define function signature (argtypes and restype): libc.abs.argtypes = [ctypes.c_int] libc.abs.restype = ctypes.c_int result = libc.abs(-42) print(f"libc abs(-42): {result} 🔗") ``` Whenever passing strings to C functions through `ctypes`, you must encode Python strings into `bytes` (`b"..."`), as C functions expect null-terminated `const char*` byte arrays ⚡! --- ### Question Why must you explicitly configure `argtypes` and `restype` on `ctypes` functions? 🧠 - [ ] a. `ctypes` defaults to 32-bit `c_int`; explicit types prevent pointer truncation and memory corruption on 64-bit platforms 🔗 - [ ] b. It activates kernel-level thread locks before executing C code - [ ] c. It prevents the C function from writing to standard output - [ ] d. Without explicit types, Python converts all return values into dictionary objects --- ### Challenge Load `libc` with `ctypes.CDLL(ctypes.util.find_library('c'))`. Set `argtypes = [ctypes.c_int]` and `restype = ctypes.c_int` for `libc.abs`. Call `libc.abs(-99)` and print the result. 🎯 <details> <summary>Solution</summary> ```python import ctypes, ctypes.util libc = ctypes.CDLL(ctypes.util.find_library('c')) libc.abs.argtypes = [ctypes.c_int] libc.abs.restype = ctypes.c_int print(libc.abs(-99)) ``` </details>

Checkpoint

Why must you explicitly configure `argtypes` and `restype` on `ctypes` functions? 🧠

Practice

Load `libc` with `ctypes.CDLL(ctypes.util.find_library('c'))`. Set `argtypes = [ctypes.c_int]` and `restype = ctypes.c_int` for `libc.abs`. Call `libc.abs(-99)` and print the result. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks