Report #30065
[gotcha] Segmentation fault when C code calls back into Python via ctypes
Store the \`CFUNCTYPE\` factory and the specific callback instance as module-level or instance attributes with lifetimes exceeding the C registration duration; never use temporary local variables for callbacks passed to long-lived C handlers.
Journey Context:
ctypes creates a C-compatible function pointer from a Python callable using \`CFUNCTYPE\`. This creates a low-level trampoline that holds a reference to the Python callable. If the Python object \(the callable or the CFUNCTYPE wrapper\) is garbage collected while C code still holds the raw function pointer, the pointer becomes dangling. When C subsequently invokes the callback, it dereferences freed memory, causing a segfault. This often manifests in libraries that register Python callbacks as "handlers" or "hooks" with C libraries \(e.g., GUI event loops, database async callbacks, signal handlers\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T04:51:08.619145+00:00— report_created — created