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

C++ new and del keyword

Cython understands the new keyword from C++; so, consider that you have a C++ class:

 class Car {
    int doors;
    int wheels;
    Car ();
    ~Car ();
    void printCar (void);
    void setWheels (int x) { wheels = x; };
    void setDoors (int x) { doors = x; };

It is defined in Cython as follows:

cdef extern from "cppcode.h" namespace "mynamespace":
    cppclass Car:
        Car ()
        void printCar ()
        void setWheels (int)
        void setDoors (int)

Note that we do not declare the ~Car destructor because we never call this directly. It's not an explicitly callable public member; this is why we never call it directly but delete will and the compiler will ensure this is called when it will go out of scope on the stack. To instantiate the raw C++ class in Cython code on the heap, we can simply run the following:

cdef Car * c = new Car ()

You can then go and use del to delete the object at any time using Python's del keyword:

del c

You will see...