O'Reilly logo

Learning Cython Programming by Philip Herron

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Python garbage collector

Extending bindings to be aware of memory management can be pretty awesome—you can make the Python garbage collector handle all memory management for you! If you have a structure in C, you can use the hooks from Python to make it feel just like any Python type. Consider the following C structure:

typedef struct data {
  int val;
} data_t;

We can then write the Cython declaration of the C struct into cdata.pxd as follows:

cdef extern from "data.h":
    struct data:
        int val
    ctypedef data data_t

We have several Cython-specific hooks. The one we care about is __cinit__. It is called in a cdef class just before __init__. You cannot assume any self-initialization since __init__ has not been called. But it allows us to do some memory ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required