Wrap a c-library with pyrex and callback as python method

gcb = None

cdef extern from "signal.h":
        ctypedef void (*sighandler_t)(int)
        sighandler_t signal(int signum, sighandler_t handler)

# signal handler function does not have callback context data, save the python callback in module global variable
cdef void _sighandler_wrapper (int signum):
        gcb (signum)

cdef class SIGNAL:
        def __init__(self, signum):
                signal (signum, _sighandler_wrapper)

        def main_loop (self):
                while (1): pass

        def set_callback (self, cb):
                global gcb
                gcb = cb

import pysig

def test_cb (i):
        print 'test_cb', i

s=pysig.SIGNAL (12)
s.set_callback (test_cb)
s.main_loop ()

$ pyrexc pysig.pyx
$ gcc -c -fPIC pysig.c -I /usr/include/python2.4/
$ gcc --shared pysig.o -o pysig.so
$ python ./test.py

In another terminal
$ pkill -12 python


Leave a Reply

Your email address will not be published. Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha