There is an alternative way to solve this problem if you do not want your C Extension (or ctypes DLL) to be tied to Python, such as a case where you want to create a C library with bindings in multiple languages, you must allow your C Extension to run for long periods, and you can modify the C Extension:
Include the signal header in the C Extension.
#include <signal.h>
Create a signal handler typedef in the C Extension.
typedef void (*sighandler_t)(int);
Add signal handlers in the C extension that will perform the actions necessary to interrupt any long running code (set a stop flag, etc.), and save the existing Python signal handlers.
sighandler_t old_sig_int_handler = signal(SIGINT, your_sig_handler);
sighandler_t old_sig_term_handler = signal(SIGTERM, your_sig_handler);
Restore the existing signal handlers whenever the C extension returns. This step ensures that the Python signal handlers are re-applied.
signal(SIGINT, old_sig_int_handler);
signal(SIGTERM, old_sig_term_handler);
If the long-running code is interrupted (flag, etc.), return control to Python with a return code indicating the signal number.
return SIGINT;
In Python, send the signal received in the C extension.
import os
import signal
status = c_extension.run()
if status in [signal.SIGINT, signal.SIGTERM]:
os.kill(os.getpid(), status)
Python will perform the action you are expecting, such as raising a KeyboardInterrupt for SIGINT.