Book Image

Learning Cython Programming (Second Edition) - Second Edition

By : Philip Herron
Book Image

Learning Cython Programming (Second Edition) - Second Edition

By: Philip Herron

Overview of this book

Cython is a hybrid programming language used to write C extensions for Python language. Combining the practicality of Python and speed and ease of the C language it’s an exciting language worth learning if you want to build fast applications with ease. This new edition of Learning Cython Programming shows you how to get started, taking you through the fundamentals so you can begin to experience its unique powers. You’ll find out how to get set up, before exploring the relationship between Python and Cython. You’ll also look at debugging Cython, before moving on to C++ constructs, Caveat on C++ usage, Python threading and GIL in Cython. Finally, you’ll learn object initialization and compile time, and gain a deeper insight into Python 3, which will help you not only become a confident Cython developer, but a much more fluent Python developer too.
Table of Contents (14 chapters)
Learning Cython Programming Second Edition
About the Author
About the Reviewer

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&gt...