Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Cython Programming (Second Edition) - Second Edition

You're reading from  Learning Cython Programming (Second Edition) - Second Edition

Product type Book
Published in Feb 2016
Publisher Packt
ISBN-13 9781783551675
Pages 110 pages
Edition 2nd Edition
Languages
Author (1):
Philip Herron Philip Herron
Profile icon Philip Herron

Callbacks from Python to C/C++


Callbacks are used extensively in asynchronous systems. Libraries such as libevent provide a powerful asynchronous core to process events. Let's build an example to set a C function as a callback into a Python backend, which will notify back again into the C code. Firstly, we will declare a public callback function typedef:

cdef public:
    ctypedef void (*callback)(int)

This will output a callback typedef. Next, we can declare a global callback on the stack:

cdef callback GlobalCallback

Once this is set, we can then notify the callback easily. Next, we need a way to set the callback and another to call the callback:

cdef public void SetCallback(callback cb):
    global GlobalCallback
    GlobalCallback = cb

Notice the global keyword from Python through which the compiler knows to use the global keyword and not create a temporary instance from within that suite:

cdef public void Notify(int value):
    global GlobalCallback
    if GlobalCallback != <callback>...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}