Using C libraries

Apart from writing fast code, one of the main use cases of Cython isto call external C libraries from Python code. As Cython codecompiles down to C code itself, it is actually trivial to call Cfunctions directly in the code. The following gives a completeexample for using (and wrapping) an external C library in Cython code,including appropriate error handling and considerations aboutdesigning a suitable API for Python and Cython code.

Imagine you need an efficient way to store integer values in a FIFOqueue. Since memory really matters, and the values are actuallycoming from C code, you cannot afford to create and store Pythonint objects in a list or deque. So you look out for a queueimplementation in C.

After some web search, you find the C-algorithms library [CAlg] anddecide to use its double ended queue implementation. To make thehandling easier, however, you decide to wrap it in a Python extensiontype that can encapsulate all memory management.

[CAlg]Simon Howard, C Algorithms library, http://c-algorithms.sourceforge.net/

Defining external declarations

You can download CAlg here.

The C API of the queue implementation, which is defined in the headerfile c-algorithms/src/queue.h, essentially looks like this:

  1. /* queue.h */
  2.  
  3. typedef struct _Queue Queue;
  4. typedef void *QueueValue;
  5.  
  6. Queue *queue_new(void);
  7. void queue_free(Queue *queue);
  8.  
  9. int queue_push_head(Queue *queue, QueueValue data);
  10. QueueValue queue_pop_head(Queue *queue);
  11. QueueValue queue_peek_head(Queue *queue);
  12.  
  13. int queue_push_tail(Queue *queue, QueueValue data);
  14. QueueValue queue_pop_tail(Queue *queue);
  15. QueueValue queue_peek_tail(Queue *queue);
  16.  
  17. int queue_is_empty(Queue *queue);

To get started, the first step is to redefine the C API in a .pxdfile, say, cqueue.pxd:

  1. # cqueue.pxd
  2.  
  3. cdef extern from "c-algorithms/src/queue.h":
  4. ctypedef struct Queue:
  5. pass
  6. ctypedef void* QueueValue
  7.  
  8. Queue* queue_new()
  9. void queue_free(Queue* queue)
  10.  
  11. int queue_push_head(Queue* queue, QueueValue data)
  12. QueueValue queue_pop_head(Queue* queue)
  13. QueueValue queue_peek_head(Queue* queue)
  14.  
  15. int queue_push_tail(Queue* queue, QueueValue data)
  16. QueueValue queue_pop_tail(Queue* queue)
  17. QueueValue queue_peek_tail(Queue* queue)
  18.  
  19. bint queue_is_empty(Queue* queue)

Note how these declarations are almost identical to the header filedeclarations, so you can often just copy them over. However, you donot need to provide all declarations as above, just those that youuse in your code or in other declarations, so that Cython gets to seea sufficient and consistent subset of them. Then, consider adaptingthem somewhat to make them more comfortable to work with in Cython.

Specifically, you should take care of choosing good argument namesfor the C functions, as Cython allows you to pass them as keywordarguments. Changing them later on is a backwards incompatible APImodification. Choosing good names right away will make thesefunctions more pleasant to work with from Cython code.

One noteworthy difference to the header file that we use above is thedeclaration of the Queue struct in the first line. Queue isin this case used as an opaque handle; only the library that iscalled knows what is really inside. Since no Cython code needs toknow the contents of the struct, we do not need to declare itscontents, so we simply provide an empty definition (as we do not wantto declare the _Queue type which is referenced in the C header)[1].

[1]There’s a subtle difference between cdef struct Queue: passand ctypedef struct Queue: pass. The former declares atype which is referenced in C code as struct Queue, whilethe latter is referenced in C as Queue. This is a Clanguage quirk that Cython is not able to hide. Most modern Clibraries use the ctypedef kind of struct.

Another exception is the last line. The integer return value of thequeue_is_empty() function is actually a C boolean value, i.e. theonly interesting thing about it is whether it is non-zero or zero,indicating if the queue is empty or not. This is best expressed byCython’s bint type, which is a normal int type when used in Cbut maps to Python’s boolean values True and False whenconverted to a Python object. This way of tightening declarations ina .pxd file can often simplify the code that uses them.

It is good practice to define one .pxd file for each library thatyou use, and sometimes even for each header file (or functional group)if the API is large. That simplifies their reuse in other projects.Sometimes, you may need to use C functions from the standard Clibrary, or want to call C-API functions from CPython directly. Forcommon needs like this, Cython ships with a set of standard .pxdfiles that provide these declarations in a readily usable way that isadapted to their use in Cython. The main packages are cpython,libc and libcpp. The NumPy library also has a standard.pxd file numpy, as it is often used in Cython code. SeeCython’s Cython/Includes/ source package for a complete list ofprovided .pxd files.

Writing a wrapper class

After declaring our C library’s API, we can start to design the Queueclass that should wrap the C queue. It will live in a file calledqueue.pyx. [2]

[2]Note that the name of the .pyx file must be different fromthe cqueue.pxd file with declarations from the C library,as both do not describe the same code. A .pxd file next toa .pyx file with the same name defines exporteddeclarations for code in the .pyx file. As thecqueue.pxd file contains declarations of a regular Clibrary, there must not be a .pyx file with the same namethat Cython associates with it.

Here is a first start for the Queue class:

  1. # queue.pyx
  2.  
  3. cimport cqueue
  4.  
  5. cdef class Queue:
  6. cdef cqueue.Queue* _c_queue
  7.  
  8. def __cinit__(self):
  9. self._c_queue = cqueue.queue_new()

Note that it says cinit rather than init. Whileinit is available as well, it is not guaranteed to be run (forinstance, one could create a subclass and forget to call theancestor’s constructor). Because not initializing C pointers oftenleads to hard crashes of the Python interpreter, Cython providescinit which is always called immediately on construction,before CPython even considers calling init, and whichtherefore is the right place to initialise cdef fields of the newinstance. However, as cinit is called during objectconstruction, self is not fully constructed yet, and one mustavoid doing anything with self but assigning to cdef fields.

Note also that the above method takes no parameters, although subtypesmay want to accept some. A no-arguments cinit() method is aspecial case here that simply does not receive any parameters thatwere passed to a constructor, so it does not prevent subclasses fromadding parameters. If parameters are used in the signature ofcinit(), they must match those of any declared initmethod of classes in the class hierarchy that are used to instantiatethe type.

Memory management

Before we continue implementing the other methods, it is important tounderstand that the above implementation is not safe. In caseanything goes wrong in the call to queue_new(), this code willsimply swallow the error, so we will likely run into a crash later on.According to the documentation of the queue_new() function, theonly reason why the above can fail is due to insufficient memory. Inthat case, it will return NULL, whereas it would normally return apointer to the new queue.

The Python way to get out of this is to raise a MemoryError [3].We can thus change the init function as follows:

  1. # queue.pyx
  2.  
  3. cimport cqueue
  4.  
  5. cdef class Queue:
  6. cdef cqueue.Queue* _c_queue
  7.  
  8. def __cinit__(self):
  9. self._c_queue = cqueue.queue_new()
  10. if self._c_queue is NULL:
  11. raise MemoryError()
[3]In the specific case of a MemoryError, creating a newexception instance in order to raise it may actually fail becausewe are running out of memory. Luckily, CPython provides a C-APIfunction PyErr_NoMemory() that safely raises the rightexception for us. Cython automaticallysubstitutes this C-API call whenever you write raise
MemoryError
or raise MemoryError(). If you use an olderversion, you have to cimport the C-API function from the standardpackage cpython.exc and call it directly.

The next thing to do is to clean up when the Queue instance is nolonger used (i.e. all references to it have been deleted). To thisend, CPython provides a callback that Cython makes available as aspecial method dealloc(). In our case, all we have to do isto free the C Queue, but only if we succeeded in initialising it inthe init method:

  1. def __dealloc__(self):
  2. if self._c_queue is not NULL:
  3. cqueue.queue_free(self._c_queue)

Compiling and linking

At this point, we have a working Cython module that we can test. Tocompile it, we need to configure a setup.py script for setuptools.Here is the most basic script for compiling a Cython module:

  1. from setuptools import Extension, setup
  2. from Cython.Build import cythonize
  3.  
  4. setup(
  5. ext_modules = cythonize([Extension("queue", ["queue.pyx"])])
  6. )

To build against the external C library, we need to make sure Cython finds the necessary libraries.There are two ways to archive this. First we can tell setuptools where to findthe c-source to compile the queue.c implementation automatically. Alternatively,we can build and install C-Alg as system library and dynamically link it. The latter is usefulif other applications also use C-Alg.

Static Linking

To build the c-code automatically we need to include compiler directives in queue.pyx:

  1. # distutils: sources = c-algorithms/src/queue.c
  2. # distutils: include_dirs = c-algorithms/src/
  3.  
  4. cimport cqueue
  5.  
  6. cdef class Queue:
  7. cdef cqueue.Queue* _c_queue
  8. def __cinit__(self):
  9. self._c_queue = cqueue.queue_new()
  10. if self._c_queue is NULL:
  11. raise MemoryError()
  12.  
  13. def __dealloc__(self):
  14. if self._c_queue is not NULL:
  15. cqueue.queue_free(self._c_queue)

The sources compiler directive gives the path of the Cfiles that setuptools is going to compile andlink (statically) into the resulting extension module.In general all relevant header files should be found in include_dirs.Now we can build the project using:

  1. $ python setup.py build_ext -i

And test whether our build was successful:

  1. $ python -c 'import queue; Q = queue.Queue()'

Dynamic Linking

Dynamic linking is useful, if the library we are going to wrap is alreadyinstalled on the system. To perform dynamic linking we first need tobuild and install c-alg.

To build c-algorithms on your system:

  1. $ cd c-algorithms
  2. $ sh autogen.sh
  3. $ ./configure
  4. $ make

to install CAlg run:

  1. $ make install

Afterwards the file /usr/local/lib/libcalg.so should exist.

Note

This path applies to Linux systems and may be different on other platforms,so you will need to adapt the rest of the tutorial depending on the pathwhere libcalg.so or libcalg.dll is on your system.

In this approach we need to tell the setup script to link with an external library.To do so we need to extend the setup script to install change the extension setup from

  1. ext_modules = cythonize([Extension("queue", ["queue.pyx"])])

to

  1. ext_modules = cythonize([
  2. Extension("queue", ["queue.pyx"],
  3. libraries=["calg"])
  4. ])

Now we should be able to build the project using:

  1. $ python setup.py build_ext -i

If the libcalg is not installed in a ‘normal’ location, users can provide therequired parameters externally by passing appropriate C compilerflags, such as:

  1. CFLAGS="-I/usr/local/otherdir/calg/include" \
  2. LDFLAGS="-L/usr/local/otherdir/calg/lib" \
  3. python setup.py build_ext -i

Before we run the module, we also need to make sure that libcalg is inthe LD_LIBRARY_PATH environment variable, e.g. by setting:

  1. $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

Once we have compiled the module for the first time, we can now importit and instantiate a new Queue:

  1. $ export PYTHONPATH=.
  2. $ python -c 'import queue; Q = queue.Queue()'

However, this is all our Queue class can do so far, so let’s make itmore usable.

Mapping functionality

Before implementing the public interface of this class, it is goodpractice to look at what interfaces Python offers, e.g. in itslist or collections.deque classes. Since we only need a FIFOqueue, it’s enough to provide the methods append(), peek() andpop(), and additionally an extend() method to add multiplevalues at once. Also, since we already know that all values will becoming from C, it’s best to provide only cdef methods for now, andto give them a straight C interface.

In C, it is common for data structures to store data as a void towhatever data item type. Since we only want to store int values,which usually fit into the size of a pointer type, we can avoidadditional memory allocations through a trick: we cast our int valuesto void and vice versa, and store the value directly as thepointer value.

Here is a simple implementation for the append() method:

  1. cdef append(self, int value):
  2. cqueue.queue_push_tail(self._c_queue, <void*>value)

Again, the same error handling considerations as for thecinit() method apply, so that we end up with thisimplementation instead:

  1. cdef append(self, int value):
  2. if not cqueue.queue_push_tail(self._c_queue,
  3. <void*>value):
  4. raise MemoryError()

Adding an extend() method should now be straight forward:

  1. cdef extend(self, int* values, size_t count):
  2. """Append all ints to the queue.
  3. """
  4. cdef int value
  5. for value in values[:count]: # Slicing pointer to limit the iteration boundaries.
  6. self.append(value)

This becomes handy when reading values from a C array, for example.

So far, we can only add data to the queue. The next step is to writethe two methods to get the first element: peek() and pop(),which provide read-only and destructive read access respectively.To avoid compiler warnings when casting void to int directly,we use an intermediate data type that is big enough to hold a void.Here, Py_ssize_t:

  1. cdef int peek(self):
  2. return <Py_ssize_t>cqueue.queue_peek_head(self._c_queue)
  3.  
  4. cdef int pop(self):
  5. return <Py_ssize_t>cqueue.queue_pop_head(self._c_queue)

Normally, in C, we risk losing data when we convert a larger integer typeto a smaller integer type without checking the boundaries, and Py_ssize_tmay be a larger type than int. But since we control how values are addedto the queue, we already know that all values that are in the queue fit intoan int, so the above conversion from void* to Py_ssize_t to int(the return type) is safe by design.

Handling errors

Now, what happens when the queue is empty? According to thedocumentation, the functions return a NULL pointer, which istypically not a valid value. But since we are simply casting to andfrom ints, we cannot distinguish anymore if the return value wasNULL because the queue was empty or because the value stored inthe queue was 0. In Cython code, we want the first case toraise an exception, whereas the second case should simply return0. To deal with this, we need to special case this value,and check if the queue really is empty or not:

  1. cdef int peek(self) except? -1:
  2. cdef int value = <Py_ssize_t>cqueue.queue_peek_head(self._c_queue)
  3. if value == 0:
  4. # this may mean that the queue is empty, or
  5. # that it happens to contain a 0 value
  6. if cqueue.queue_is_empty(self._c_queue):
  7. raise IndexError("Queue is empty")
  8. return value

Note how we have effectively created a fast path through the method inthe hopefully common cases that the return value is not 0. Onlythat specific case needs an additional check if the queue is empty.

The except? -1 declaration in the method signature falls into thesame category. If the function was a Python function returning aPython object value, CPython would simply return NULL internallyinstead of a Python object to indicate an exception, which wouldimmediately be propagated by the surrounding code. The problem isthat the return type is int and any int value is a valid queueitem value, so there is no way to explicitly signal an error to thecalling code. In fact, without such a declaration, there is noobvious way for Cython to know what to return on exceptions and forcalling code to even know that this method may exit with anexception.

The only way calling code can deal with this situation is to callPyErr_Occurred() when returning from a function to check if anexception was raised, and if so, propagate the exception. Thisobviously has a performance penalty. Cython therefore allows you todeclare which value it should implicitly return in the case of anexception, so that the surrounding code only needs to check for anexception when receiving this exact value.

We chose to use -1 as the exception return value as we expect itto be an unlikely value to be put into the queue. The question markin the except? -1 declaration indicates that the return value isambiguous (there may be a -1 value in the queue, after all) andthat an additional exception check using PyErr_Occurred() isneeded in calling code. Without it, Cython code that calls thismethod and receives the exception return value would silently (andsometimes incorrectly) assume that an exception has been raised. Inany case, all other return values will be passed through almostwithout a penalty, thus again creating a fast path for ‘normal’values.

Now that the peek() method is implemented, the pop() methodalso needs adaptation. Since it removes a value from the queue,however, it is not enough to test if the queue is empty after theremoval. Instead, we must test it on entry:

  1. cdef int pop(self) except? -1:
  2. if cqueue.queue_is_empty(self._c_queue):
  3. raise IndexError("Queue is empty")
  4. return <Py_ssize_t>cqueue.queue_pop_head(self._c_queue)

The return value for exception propagation is declared exactly as forpeek().

Lastly, we can provide the Queue with an emptiness indicator in thenormal Python way by implementing the bool() special method(note that Python 2 calls this method nonzero, whereas Cythoncode can use either name):

  1. def __bool__(self):
  2. return not cqueue.queue_is_empty(self._c_queue)

Note that this method returns either True or False as wedeclared the return type of the queue_is_empty() function asbint in cqueue.pxd.

Testing the result

Now that the implementation is complete, you may want to write sometests for it to make sure it works correctly. Especially doctests arevery nice for this purpose, as they provide some documentation at thesame time. To enable doctests, however, you need a Python API thatyou can call. C methods are not visible from Python code, and thusnot callable from doctests.

A quick way to provide a Python API for the class is to change themethods from cdef to cpdef. This will let Cython generate twoentry points, one that is callable from normal Python code using thePython call semantics and Python objects as arguments, and one that iscallable from C code with fast C semantics and without requiringintermediate argument conversion from or to Python types. Note that cpdefmethods ensure that they can be appropriately overridden by Pythonmethods even when they are called from Cython. This adds a tiny overheadcompared to cdef methods.

Now that we have both a C-interface and a Python interface for ourclass, we should make sure that both interfaces are consistent.Python users would expect an extend() method that accepts arbitraryiterables, whereas C users would like to have one that allows passingC arrays and C memory. Both signatures are incompatible.

We will solve this issue by considering that in C, the API could alsowant to support other input types, e.g. arrays of long or char,which is usually supported with differently named C API functions such asextend_ints(), extend_longs(), extend_chars()``, etc. This allowsus to free the method name extend() for the duck typed Python method,which can accept arbitrary iterables.

The following listing shows the complete implementation that usescpdef methods where possible:

  1. # queue.pyx
  2.  
  3. cimport cqueue
  4.  
  5. cdef class Queue:
  6. """A queue class for C integer values.
  7.  
  8. >>> q = Queue()
  9. >>> q.append(5)
  10. >>> q.peek()
  11. 5
  12. >>> q.pop()
  13. 5
  14. """
  15. cdef cqueue.Queue* _c_queue
  16. def __cinit__(self):
  17. self._c_queue = cqueue.queue_new()
  18. if self._c_queue is NULL:
  19. raise MemoryError()
  20.  
  21. def __dealloc__(self):
  22. if self._c_queue is not NULL:
  23. cqueue.queue_free(self._c_queue)
  24.  
  25. cpdef append(self, int value):
  26. if not cqueue.queue_push_tail(self._c_queue,
  27. <void*> <Py_ssize_t> value):
  28. raise MemoryError()
  29.  
  30. # The `cpdef` feature is obviously not available for the original "extend()"
  31. # method, as the method signature is incompatible with Python argument
  32. # types (Python does not have pointers). However, we can rename
  33. # the C-ish "extend()" method to e.g. "extend_ints()", and write
  34. # a new "extend()" method that provides a suitable Python interface by
  35. # accepting an arbitrary Python iterable.
  36. cpdef extend(self, values):
  37. for value in values:
  38. self.append(value)
  39.  
  40. cdef extend_ints(self, int* values, size_t count):
  41. cdef int value
  42. for value in values[:count]: # Slicing pointer to limit the iteration boundaries.
  43. self.append(value)
  44.  
  45. cpdef int peek(self) except? -1:
  46. cdef int value = <Py_ssize_t> cqueue.queue_peek_head(self._c_queue)
  47.  
  48. if value == 0:
  49. # this may mean that the queue is empty,
  50. # or that it happens to contain a 0 value
  51. if cqueue.queue_is_empty(self._c_queue):
  52. raise IndexError("Queue is empty")
  53. return value
  54.  
  55. cpdef int pop(self) except? -1:
  56. if cqueue.queue_is_empty(self._c_queue):
  57. raise IndexError("Queue is empty")
  58. return <Py_ssize_t> cqueue.queue_pop_head(self._c_queue)
  59.  
  60. def __bool__(self):
  61. return not cqueue.queue_is_empty(self._c_queue)

Now we can test our Queue implementation using a python script,for example here test_queue.py:

  1. from __future__ import print_function
  2.  
  3. import time
  4.  
  5. import queue
  6.  
  7. Q = queue.Queue()
  8.  
  9. Q.append(10)
  10. Q.append(20)
  11. print(Q.peek())
  12. print(Q.pop())
  13. print(Q.pop())
  14. try:
  15. print(Q.pop())
  16. except IndexError as e:
  17. print("Error message:", e) # Prints "Queue is empty"
  18.  
  19. i = 10000
  20.  
  21. values = range(i)
  22.  
  23. start_time = time.time()
  24.  
  25. Q.extend(values)
  26.  
  27. end_time = time.time() - start_time
  28.  
  29. print("Adding {} items took {:1.3f} msecs.".format(i, 1000 * end_time))
  30.  
  31. for i in range(41):
  32. Q.pop()
  33.  
  34. Q.pop()
  35. print("The answer is:")
  36. print(Q.pop())

As a quick test with 10000 numbers on the author’s machine indicates,using this Queue from Cython code with C int values is about fivetimes as fast as using it from Cython code with Python object values,almost eight times faster than using it from Python code in a Pythonloop, and still more than twice as fast as using Python’s highlyoptimised collections.deque type from Cython code with Pythonintegers.

Callbacks

Let’s say you want to provide a way for users to pop values from thequeue up to a certain user defined event occurs. To this end, youwant to allow them to pass a predicate function that determines whento stop, e.g.:

  1. def pop_until(self, predicate):
  2. while not predicate(self.peek()):
  3. self.pop()

Now, let us assume for the sake of argument that the C queueprovides such a function that takes a C callback function aspredicate. The API could look as follows:

  1. /* C type of a predicate function that takes a queue value and returns
  2. * -1 for errors
  3. * 0 for reject
  4. * 1 for accept
  5. */
  6. typedef int (*predicate_func)(void* user_context, QueueValue data);
  7.  
  8. /* Pop values as long as the predicate evaluates to true for them,
  9. * returns -1 if the predicate failed with an error and 0 otherwise.
  10. */
  11. int queue_pop_head_until(Queue *queue, predicate_func predicate,
  12. void* user_context);

It is normal for C callback functions to have a generic void*argument that allows passing any kind of context or state through theC-API into the callback function. We will use this to pass our Pythonpredicate function.

First, we have to define a callback function with the expectedsignature that we can pass into the C-API function:

  1. cdef int evaluate_predicate(void* context, cqueue.QueueValue value):
  2. "Callback function that can be passed as predicate_func"
  3. try:
  4. # recover Python function object from void* argument
  5. func = <object>context
  6. # call function, convert result into 0/1 for True/False
  7. return bool(func(<int>value))
  8. except:
  9. # catch any Python errors and return error indicator
  10. return -1

The main idea is to pass a pointer (a.k.a. borrowed reference) to thefunction object as the user context argument. We will call the C-APIfunction as follows:

  1. def pop_until(self, python_predicate_function):
  2. result = cqueue.queue_pop_head_until(
  3. self._c_queue, evaluate_predicate,
  4. <void*>python_predicate_function)
  5. if result == -1:
  6. raise RuntimeError("an error occurred")

The usual pattern is to first cast the Python object reference intoa void to pass it into the C-API function, and then castit back into a Python object in the C predicate callback function.The cast to void creates a borrowed reference. On the castto <object>, Cython increments the reference count of the objectand thus converts the borrowed reference back into an owned reference.At the end of the predicate function, the owned reference goes outof scope again and Cython discards it.

The error handling in the code above is a bit simplistic. Specifically,any exceptions that the predicate function raises will essentially bediscarded and only result in a plain RuntimeError() being raisedafter the fact. This can be improved by storing away the exceptionin an object passed through the context parameter and re-raising itafter the C-API function has returned -1 to indicate the error.