Calling C functions¶
Note
This page uses two different syntax variants:
Cython specific
cdef
syntax, which was designed to make type declarationsconcise and easily readable from a C/C++ perspective.Pure Python syntax which allows static Cython type declarations inpure Python code,followingPEP-484 type hintsandPEP 526 variable annotations.
To make use of C data types in Python syntax, you need to import the special
cython
module in the Python module that you want to compile, e.g.importcython
If you use the pure Python syntax we strongly recommend you use a recentCython 3 release, since significant improvements have been made herecompared to the 0.29.x releases.
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, seeUsing 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 fromachar*
value. You could use theatoi()
function, as definedby thestdlib.h
header file. This can be done as follows:
fromcython.cimports.libc.stdlibimportatoi@cython.cfuncdefparse_charptr_to_py_int(s:cython.p_char):assertsisnotcython.NULL,"byte string value is NULL"returnatoi(s)# note: atoi() has no error detection!
fromlibc.stdlibcimportatoicdefparse_charptr_to_py_int(char*s):assertsisnotNULL,"byte string value is NULL"returnatoi(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(seeSharing 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:
fromcython.cimports.cpython.versionimportPY_VERSION_HEX# Python version >= 3.2 final ?print(PY_VERSION_HEX>=0x030200F0)
fromcpython.versioncimportPY_VERSION_HEX# Python version >= 3.2 final ?print(PY_VERSION_HEX>=0x030200F0)
Cython also provides declarations for the C math library:
fromcython.cimports.libc.mathimportsin@cython.cfuncdeff(x:cython.double)->cython.double:returnsin(x*x)
fromlibc.mathcimportsincdefdoublef(doublex):returnsin(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 librarym
. For setuptools, it is enough to add it to thelibraries
parameter of theExtension()
setup:
fromsetuptoolsimportExtension,setupfromCython.Buildimportcythonizeext_modules=[Extension("demo",sources=["demo.pyx"],libraries=["m"]# Unix-like specific)]setup(name="Demos",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, theabovesin()
function is defined as follows:
cdefexternfrom"math.h":doublesin(doublex)
This declares thesin()
function in a way that makes it availableto Cython code and instructs Cython to generate C code that includesthemath.h
header file. The C compiler will see the originaldeclaration inmath.h
at compile time, but Cython does not parse“math.h” and requires a separate definition.
Just like thesin()
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 ascpdef
. This generates a Python wrapperfor it and adds it to the module dict. Here is a Cython module thatprovides direct access to the Csin()
function for Python code:
""">>> sin(0)0.0"""cdefexternfrom"math.h":cpdefdoublesin(doublex)
You get the same result when this declaration appears in the.pxd
file that belongs to the Cython module (i.e. that has the same name,seeSharing 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.
Note
External declarations must be placed in a.pxd
file in PurePython mode.
Naming parameters¶
Both C and Cython support signature declarations without parameternames like this:
cdefexternfrom"string.h":char*strstr(constchar*,constchar*)
However, this prevents Cython code from calling it with keywordarguments. It is therefore preferableto write the declaration like this instead:
cdefexternfrom"string.h":char*strstr(constchar*haystack,constchar*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:
fromcython.cimports.strstrimportstrstrdefmain():data:cython.p_char="hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh"pos=strstr(needle='akd',haystack=data)print(posisnotcython.NULL)
cdefexternfrom"string.h":char*strstr(constchar*haystack,constchar*needle)
cdefexternfrom"string.h":char*strstr(constchar*haystack,constchar*needle)cdefchar*data="hfvcakdfagbcffvschvxcdfgccbcfhvgcsnfxjh"cdefchar*pos=strstr(needle='akd',haystack=data)print(posisnotNULL)
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.