Calling C functions

This tutorial describes shortly what you need to know in order to callC library functions from Cython code. For a longer and morecomprehensive tutorial about using external C libraries, wrapping themand handling errors, see Using C libraries.

For simplicity, let’s start with a function from the standard Clibrary. This does not add any dependencies to your code, and it hasthe additional advantage that Cython already defines many suchfunctions for you. So you can just cimport and use them.

For example, let’s say you need a low-level way to parse a number froma char* value. You could use the atoi() function, as definedby the stdlib.h header file. This can be done as follows:

  1. from libc.stdlib cimport atoi
  2.  
  3. cdef parse_charptr_to_py_int(char* s):
  4. assert s is not NULL, "byte string value is NULL"
  5. return atoi(s) # note: atoi() has no error detection!

You can find a complete list of these standard cimport files inCython’s source packageCython/Includes/.They are stored in .pxd files, the standard way to provide reusableCython declarations that can be shared across modules(see Sharing Declarations Between Cython Modules).

Cython also has a complete set of declarations for CPython’s C-API.For example, to test at C compilation time which CPython versionyour code is being compiled with, you can do this:

  1. from cpython.version cimport PY_VERSION_HEX
  2.  
  3. # Python version >= 3.2 final ?
  4. print(PY_VERSION_HEX >= 0x030200F0)

Cython also provides declarations for the C math library:

  1. from libc.math cimport sin
  2.  
  3. cdef double f(double x):
  4. return sin(x * x)

Dynamic linking

The libc math library is special in that it is not linked by defaulton some Unix-like systems, such as Linux. In addition to cimporting thedeclarations, you must configure your build system to link against theshared library m. For setuptools, it is enough to add it to thelibraries parameter of the Extension() setup:

  1. from setuptools import Extension, setup
  2. from Cython.Build import cythonize
  3.  
  4. ext_modules = [
  5. Extension("demo",
  6. sources=["demo.pyx"],
  7. libraries=["m"] # Unix-like specific
  8. )
  9. ]
  10.  
  11. setup(name="Demos",
  12. ext_modules=cythonize(ext_modules))

External declarations

If you want to access C code for which Cython does not provide a readyto use declaration, you must declare them yourself. For example, theabove sin() function is defined as follows:

  1. cdef extern from "math.h":
  2. double sin(double x)

This declares the sin() function in a way that makes it availableto Cython code and instructs Cython to generate C code that includesthe math.h header file. The C compiler will see the originaldeclaration in math.h at compile time, but Cython does not parse“math.h” and requires a separate definition.

Just like the sin() function from the math library, it is possibleto declare and call into any C library as long as the module thatCython generates is properly linked against the shared or staticlibrary.

Note that you can easily export an external C function from your Cythonmodule by declaring it as cpdef. This generates a Python wrapperfor it and adds it to the module dict. Here is a Cython module thatprovides direct access to the C sin() function for Python code:

  1. """
  2. >>> sin(0)
  3. 0.0
  4. """
  5.  
  6. cdef extern from "math.h":
  7. cpdef double sin(double x)

You get the same result when this declaration appears in the .pxdfile that belongs to the Cython module (i.e. that has the same name,see Sharing Declarations Between Cython Modules).This allows the C declaration to be reused in other Cython modules,while still providing an automatically generated Python wrapper inthis specific module.

Naming parameters

Both C and Cython support signature declarations without parameternames like this:

  1. cdef extern from "string.h":
  2. char* strstr(const char*, const char*)

However, this prevents Cython code from calling it with keywordarguments. It is therefore preferableto write the declaration like this instead:

  1. cdef extern from "string.h":
  2. char* strstr(const char *haystack, const char *needle)

You can now make it clear which of the two arguments does what inyour call, thus avoiding any ambiguities and often making your codemore readable:

  1. cdef extern from "string.h":
  2. char* strstr(const char *haystack, const char *needle)
  3.  
  4. cdef char* data = "hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh"
  5.  
  6. cdef char* pos = strstr(needle='akd', haystack=data)
  7. print(pos is not NULL)

Note that changing existing parameter names later is a backwardsincompatible API modification, just as for Python code. Thus, ifyou provide your own declarations for external C or C++ functions,it is usually worth the additional bit of effort to choose thenames of their arguments well.