C Struct Memory Layout & CFFI Fundamentals
Interfacing with native C libraries requires matching exact binary struct layouts and memory alignments. `ctypes.Structure` and CFFI map native C byte structures directly into Python memory without serialization overhead 🛠️.
import ctypes
# C struct: struct Point { int x; int y; };
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)]
pt = Point(15, 25)
print(f"Memory size: {ctypes.sizeof(pt)} bytes")
print(f"Values: x={pt.x}, y={pt.y} 🛠️")
# 98. C Struct Memory Layout & CFFI Fundamentals Interfacing with native C libraries requires matching exact binary struct layouts and memory alignments. `ctypes.Structure` and CFFI map native C byte structures directly into Python memory without serialization overhead 🛠️. ```python import ctypes # C struct: struct Point { int x; int y; }; class Point(ctypes.Structure): _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)] pt = Point(15, 25) print(f"Memory size: {ctypes.sizeof(pt)} bytes") print(f"Values: x={pt.x}, y={pt.y} 🛠️") ``` Under C ABI conventions, compilers insert padding bytes into structs to satisfy CPU alignment requirements (e.g. 4-byte or 8-byte boundaries). `ctypes.sizeof()` reports the true aligned memory footprint in RAM ⚡! --- ### Question What makes CFFI safer and more robust than traditional manual `ctypes` bindings? 🧠 - [ ] a. CFFI parses genuine C header declarations directly via `cdef()`, catching ABI mismatch errors at compile/import time 🛠️ - [ ] b. CFFI automatically compiles Python functions into native machine code - [ ] c. CFFI runs in a dedicated web browser sandbox environment - [ ] d. CFFI does not require an operating system C runtime library --- ### Challenge Define a `ctypes.Structure` subclass `Pixel` with `_fields_ = [('r', ctypes.c_uint8), ('g', ctypes.c_uint8), ('b', ctypes.c_uint8)]`. Instantiate `Pixel(255, 128, 0)`. Print `(ctypes.sizeof(Pixel), p.r, p.g, p.b)`. 🎯 <details> <summary>Solution</summary> ```python import ctypes class Pixel(ctypes.Structure): _fields_ = [('r', ctypes.c_uint8), ('g', ctypes.c_uint8), ('b', ctypes.c_uint8)] p = Pixel(255, 128, 0) print((ctypes.sizeof(Pixel), p.r, p.g, p.b)) ``` </details>