1.. highlight:: cython 2 3.. _external-C-code: 4 5********************************** 6Interfacing with External C Code 7********************************** 8 9One of the main uses of Cython is wrapping existing libraries of C code. This 10is achieved by using external declarations to declare the C functions and 11variables from the library that you want to use. 12 13You can also use public declarations to make C functions and variables defined 14in a Cython module available to external C code. The need for this is expected 15to be less frequent, but you might want to do it, for example, if you are 16`embedding Python`_ in another application as a scripting language. Just as a 17Cython module can be used as a bridge to allow Python code to call C code, it 18can also be used to allow C code to call Python code. 19 20.. _embedding Python: https://web.archive.org/web/20120225082358/http://www.freenet.org.nz:80/python/embeddingpyrex/ 21 22External declarations 23======================= 24 25By default, C functions and variables declared at the module level are local 26to the module (i.e. they have the C static storage class). They can also be 27declared extern to specify that they are defined elsewhere, for example,:: 28 29 cdef extern int spam_counter 30 31 cdef extern void order_spam(int tons) 32 33Referencing C header files 34--------------------------- 35 36When you use an extern definition on its own as in the examples above, Cython 37includes a declaration for it in the generated C file. This can cause problems 38if the declaration doesn't exactly match the declaration that will be seen by 39other C code. If you're wrapping an existing C library, for example, it's 40important that the generated C code is compiled with exactly the same 41declarations as the rest of the library. 42 43To achieve this, you can tell Cython that the declarations are to be found in a 44C header file, like this:: 45 46 cdef extern from "spam.h": 47 48 int spam_counter 49 50 void order_spam(int tons) 51 52The ``cdef extern`` from clause does three things: 53 541. It directs Cython to place a ``#include`` statement for the named header file in 55 the generated C code. 562. It prevents Cython from generating any C code 57 for the declarations found in the associated block. 583. It treats all declarations within the block as though they started with 59 ``cdef extern``. 60 61It's important to understand that Cython does not itself read the C header 62file, so you still need to provide Cython versions of any declarations from it 63that you use. However, the Cython declarations don't always have to exactly 64match the C ones, and in some cases they shouldn't or can't. In particular: 65 66#. Leave out any platform-specific extensions to C declarations such as 67 ``__declspec()``. 68 69#. If the header file declares a big struct and you only want to use a few 70 members, you only need to declare the members you're interested in. Leaving 71 the rest out doesn't do any harm, because the C compiler will use the full 72 definition from the header file. 73 74 In some cases, you might not need any of the struct's members, in which 75 case you can just put pass in the body of the struct declaration, e.g.:: 76 77 cdef extern from "foo.h": 78 struct spam: 79 pass 80 81 .. note:: 82 83 you can only do this inside a ``cdef extern from`` block; struct 84 declarations anywhere else must be non-empty. 85 86#. If the header file uses ``typedef`` names such as :c:type:`word` to refer 87 to platform-dependent flavours of numeric types, you will need a 88 corresponding :keyword:`ctypedef` statement, but you don't need to match 89 the type exactly, just use something of the right general kind (int, float, 90 etc). For example,:: 91 92 ctypedef int word 93 94 will work okay whatever the actual size of a :c:type:`word` is (provided the header 95 file defines it correctly). Conversion to and from Python types, if any, will also 96 be used for this new type. 97 98#. If the header file uses macros to define constants, translate them into a 99 normal external variable declaration. You can also declare them as an 100 :keyword:`enum` if they contain normal :c:type:`int` values. Note that 101 Cython considers :keyword:`enum` to be equivalent to :c:type:`int`, so do 102 not do this for non-int values. 103 104#. If the header file defines a function using a macro, declare it as though 105 it were an ordinary function, with appropriate argument and result types. 106 107#. For archaic reasons C uses the keyword ``void`` to declare a function 108 taking no parameters. In Cython as in Python, simply declare such functions 109 as :meth:`foo()`. 110 111A few more tricks and tips: 112 113* If you want to include a C header because it's needed by another header, but 114 don't want to use any declarations from it, put pass in the extern-from 115 block:: 116 117 cdef extern from "spam.h": 118 pass 119 120* If you want to include a system header, put angle brackets inside the quotes:: 121 122 cdef extern from "<sysheader.h>": 123 ... 124 125* If you want to include some external declarations, but don't want to specify 126 a header file (because it's included by some other header that you've 127 already included) you can put ``*`` in place of the header file name:: 128 129 cdef extern from *: 130 ... 131 132* If a ``cdef extern from "inc.h"`` block is not empty and contains only 133 function or variable declarations (and no type declarations of any kind), 134 Cython will put the ``#include "inc.h"`` statement after all 135 declarations generated by Cython. This means that the included file 136 has access to the variables, functions, structures, ... which are 137 declared by Cython. 138 139Implementing functions in C 140--------------------------- 141 142When you want to call C code from a Cython module, usually that code 143will be in some external library that you link your extension against. 144However, you can also directly compile C (or C++) code as part of your 145Cython module. In the ``.pyx`` file, you can put something like:: 146 147 cdef extern from "spam.c": 148 void order_spam(int tons) 149 150Cython will assume that the function ``order_spam()`` is defined in the 151file ``spam.c``. If you also want to cimport this function from another 152module, it must be declared (not extern!) in the ``.pxd`` file:: 153 154 cdef void order_spam(int tons) 155 156For this to work, the signature of ``order_spam()`` in ``spam.c`` must 157match the signature that Cython uses, in particular the function must 158be static: 159 160.. code-block:: c 161 162 static void order_spam(int tons) 163 { 164 printf("Ordered %i tons of spam!\n", tons); 165 } 166 167 168.. _struct-union-enum-styles: 169 170Styles of struct, union and enum declaration 171---------------------------------------------- 172 173There are two main ways that structs, unions and enums can be declared in C 174header files: using a tag name, or using a typedef. There are also some 175variations based on various combinations of these. 176 177It's important to make the Cython declarations match the style used in the 178header file, so that Cython can emit the right sort of references to the type 179in the code it generates. To make this possible, Cython provides two different 180syntaxes for declaring a struct, union or enum type. The style introduced 181above corresponds to the use of a tag name. To get the other style, you prefix 182the declaration with :keyword:`ctypedef`, as illustrated below. 183 184The following table shows the various possible styles that can be found in a 185header file, and the corresponding Cython declaration that you should put in 186the ``cdef extern`` from block. Struct declarations are used as an example; the 187same applies equally to union and enum declarations. 188 189+-------------------------+---------------------------------------------+-----------------------------------------------------------------------+ 190| C code | Possibilities for corresponding Cython Code | Comments | 191+=========================+=============================================+=======================================================================+ 192| .. sourcecode:: c | :: | Cython will refer to the as ``struct Foo`` in the generated C code. | 193| | | | 194| struct Foo { | cdef struct Foo: | | 195| ... | ... | | 196| }; | | | 197+-------------------------+---------------------------------------------+-----------------------------------------------------------------------+ 198| .. sourcecode:: c | :: | Cython will refer to the type simply as ``Foo`` in | 199| | | the generated C code. | 200| typedef struct { | ctypedef struct Foo: | | 201| ... | ... | | 202| } Foo; | | | 203+-------------------------+---------------------------------------------+-----------------------------------------------------------------------+ 204| .. sourcecode:: c | :: | If the C header uses both a tag and a typedef with *different* | 205| | | names, you can use either form of declaration in Cython | 206| typedef struct foo { | cdef struct foo: | (although if you need to forward reference the type, | 207| ... | ... | you'll have to use the first form). | 208| } Foo; | ctypedef foo Foo #optional | | 209| | | | 210| | or:: | | 211| | | | 212| | ctypedef struct Foo: | | 213| | ... | | 214+-------------------------+---------------------------------------------+-----------------------------------------------------------------------+ 215| .. sourcecode:: c | :: | If the header uses the *same* name for the tag and typedef, you | 216| | | won't be able to include a :keyword:`ctypedef` for it -- but then, | 217| typedef struct Foo { | cdef struct Foo: | it's not necessary. | 218| ... | ... | | 219| } Foo; | | | 220+-------------------------+---------------------------------------------+-----------------------------------------------------------------------+ 221 222See also use of :ref:`external_extension_types`. 223Note that in all the cases below, you refer to the type in Cython code simply 224as :c:type:`Foo`, not ``struct Foo``. 225 226Accessing Python/C API routines 227--------------------------------- 228 229One particular use of the ``cdef extern from`` statement is for gaining access to 230routines in the Python/C API. For example,:: 231 232 cdef extern from "Python.h": 233 234 object PyString_FromStringAndSize(char *s, Py_ssize_t len) 235 236will allow you to create Python strings containing null bytes. 237 238Special Types 239-------------- 240 241Cython predefines the name ``Py_ssize_t`` for use with Python/C API routines. To 242make your extensions compatible with 64-bit systems, you should always use 243this type where it is specified in the documentation of Python/C API routines. 244 245Windows Calling Conventions 246---------------------------- 247 248The ``__stdcall`` and ``__cdecl`` calling convention specifiers can be used in 249Cython, with the same syntax as used by C compilers on Windows, for example,:: 250 251 cdef extern int __stdcall FrobnicateWindow(long handle) 252 253 cdef void (__stdcall *callback)(void *) 254 255If ``__stdcall`` is used, the function is only considered compatible with 256other ``__stdcall`` functions of the same signature. 257 258 259.. _resolve-conflicts: 260 261Resolving naming conflicts - C name specifications 262-------------------------------------------------- 263 264Each Cython module has a single module-level namespace for both Python and C 265names. This can be inconvenient if you want to wrap some external C functions 266and provide the Python user with Python functions of the same names. 267 268Cython provides a couple of different ways of solving this problem. The best 269way, especially if you have many C functions to wrap, is to put the extern 270C function declarations into a ``.pxd`` file and thus a different namespace, 271using the facilities described in :ref:`sharing declarations between Cython 272modules <sharing-declarations>`. Writing them into a ``.pxd`` file allows 273their reuse across modules, avoids naming collisions in the normal Python way 274and even makes it easy to rename them on cimport. For example, if your 275``decl.pxd`` file declared a C function ``eject_tomato``:: 276 277 cdef extern from "myheader.h": 278 void eject_tomato(float speed) 279 280then you can cimport and wrap it in a ``.pyx`` file as follows:: 281 282 from decl cimport eject_tomato as c_eject_tomato 283 284 def eject_tomato(speed): 285 c_eject_tomato(speed) 286 287or simply cimport the ``.pxd`` file and use it as prefix:: 288 289 cimport decl 290 291 def eject_tomato(speed): 292 decl.eject_tomato(speed) 293 294Note that this has no runtime lookup overhead, as it would in Python. 295Cython resolves the names in the ``.pxd`` file at compile time. 296 297For special cases where namespacing or renaming on import is not enough, 298e.g. when a name in C conflicts with a Python keyword, you can use a C name 299specification to give different Cython and C names to the C function at 300declaration time. Suppose, for example, that you want to wrap an external 301C function called :func:`yield`. If you declare it as:: 302 303 cdef extern from "myheader.h": 304 void c_yield "yield" (float speed) 305 306then its Cython visible name will be ``c_yield``, whereas its name in C 307will be ``yield``. You can then wrap it with:: 308 309 def call_yield(speed): 310 c_yield(speed) 311 312As for functions, C names can be specified for variables, structs, unions, 313enums, struct and union members, and enum values. For example:: 314 315 cdef extern int one "eins", two "zwei" 316 cdef extern float three "drei" 317 318 cdef struct spam "SPAM": 319 int i "eye" 320 321 cdef enum surprise "inquisition": 322 first "alpha" 323 second "beta" = 3 324 325Note that Cython will not do any validation or name mangling on the string 326you provide. It will inject the bare text into the C code unmodified, so you 327are entirely on your own with this feature. If you want to declare a name 328``xyz`` and have Cython inject the text "make the C compiler fail here" into 329the C file for it, you can do this using a C name declaration. Consider this 330an advanced feature, only for the rare cases where everything else fails. 331 332Including verbatim C code 333------------------------- 334 335For advanced use cases, Cython allows you to directly write C code 336as "docstring" of a ``cdef extern from`` block: 337 338.. literalinclude:: ../../examples/userguide/external_C_code/c_code_docstring.pyx 339 340The above is essentially equivalent to having the C code in a file 341``header.h`` and writing :: 342 343 cdef extern from "header.h": 344 long square(long x) 345 void assign(long& x, long y) 346 347It is also possible to combine a header file and verbatim C code:: 348 349 cdef extern from "badheader.h": 350 """ 351 /* This macro breaks stuff */ 352 #undef int 353 """ 354 # Stuff from badheader.h 355 356In this case, the C code ``#undef int`` is put right after 357``#include "badheader.h"`` in the C code generated by Cython. 358 359Note that the string is parsed like any other docstring in Python. 360If you require character escapes to be passed into the C code file, 361use a raw docstring, i.e. ``r""" ... """``. 362 363 364Using Cython Declarations from C 365================================ 366 367Cython provides two methods for making C declarations from a Cython module 368available for use by external C code---public declarations and C API 369declarations. 370 371.. note:: 372 373 You do not need to use either of these to make declarations from one 374 Cython module available to another Cython module – you should use the 375 :keyword:`cimport` statement for that. Sharing Declarations Between Cython Modules. 376 377Public Declarations 378--------------------- 379 380You can make C types, variables and functions defined in a Cython module 381accessible to C code that is linked together with the Cython-generated C file, 382by declaring them with the public keyword:: 383 384 cdef public struct Bunny: # public type declaration 385 int vorpalness 386 387 cdef public int spam # public variable declaration 388 389 cdef public void grail(Bunny *) # public function declaration 390 391If there are any public declarations in a Cython module, a header file called 392:file:`modulename.h` file is generated containing equivalent C declarations for 393inclusion in other C code. 394 395A typical use case for this is building an extension module from multiple 396C sources, one of them being Cython generated (i.e. with something like 397``Extension("grail", sources=["grail.pyx", "grail_helper.c"])`` in ``setup.py``. 398In this case, the file ``grail_helper.c`` just needs to add 399``#include "grail.h"`` in order to access the public Cython variables. 400 401A more advanced use case is embedding Python in C using Cython. 402In this case, make sure to call Py_Initialize() and Py_Finalize(). 403For example, in the following snippet that includes :file:`grail.h`: 404 405.. code-block:: c 406 407 #include <Python.h> 408 #include "grail.h" 409 410 int main() { 411 Py_Initialize(); 412 initgrail(); /* Python 2.x only ! */ 413 Bunny b; 414 grail(b); 415 Py_Finalize(); 416 } 417 418This C code can then be built together with the Cython-generated C code 419in a single program (or library). 420 421In Python 3.x, calling the module init function directly should be avoided. Instead, 422use the `inittab mechanism <https://docs.python.org/3/c-api/import.html#c._inittab>`_ 423to link Cython modules into a single shared library or program. 424 425.. code-block:: c 426 427 err = PyImport_AppendInittab("grail", PyInit_grail); 428 Py_Initialize(); 429 grail_module = PyImport_ImportModule("grail"); 430 431If the Cython module resides within a package, then the name of the ``.h`` 432file consists of the full dotted name of the module, e.g. a module called 433:mod:`foo.spam` would have a header file called :file:`foo.spam.h`. 434 435.. NOTE:: 436 437 On some operating systems like Linux, it is also possible to first 438 build the Cython extension in the usual way and then link against 439 the resulting ``.so`` file like a dynamic library. 440 Beware that this is not portable, so it should be avoided. 441 442.. _api: 443 444C API Declarations 445------------------- 446 447The other way of making declarations available to C code is to declare them 448with the :keyword:`api` keyword. You can use this keyword with C functions and 449extension types. A header file called :file:`modulename_api.h` is produced 450containing declarations of the functions and extension types, and a function 451called :func:`import_modulename`. 452 453C code wanting to use these functions or extension types needs to include the 454header and call the :func:`import_modulename` function. The other functions 455can then be called and the extension types used as usual. 456 457If the C code wanting to use these functions is part of more than one shared 458library or executable, then :func:`import_modulename` function needs to be 459called in each of the shared libraries which use these functions. If you 460crash with a segmentation fault (SIGSEGV on linux) when calling into one of 461these api calls, this is likely an indication that the shared library which 462contains the api call which is generating the segmentation fault does not call 463the :func:`import_modulename` function before the api call which crashes. 464 465Any public C type or extension type declarations in the Cython module are also 466made available when you include :file:`modulename_api.h`.: 467 468.. literalinclude:: ../../examples/userguide/external_C_code/delorean.pyx 469 470.. literalinclude:: ../../examples/userguide/external_C_code/marty.c 471 :language: C 472 473.. note:: 474 475 Any types defined in the Cython module that are used as argument or 476 return types of the exported functions will need to be declared public, 477 otherwise they won't be included in the generated header file, and you will 478 get errors when you try to compile a C file that uses the header. 479 480Using the :keyword:`api` method does not require the C code using the 481declarations to be linked with the extension module in any way, as the Python 482import machinery is used to make the connection dynamically. However, only 483functions can be accessed this way, not variables. Note also that for the 484module import mechanism to be set up correctly, the user must call 485Py_Initialize() and Py_Finalize(); if you experience a segmentation fault in 486the call to :func:`import_modulename`, it is likely that this wasn't done. 487 488You can use both :keyword:`public` and :keyword:`api` on the same function to 489make it available by both methods, e.g.:: 490 491 cdef public api void belt_and_braces(): 492 ... 493 494However, note that you should include either :file:`modulename.h` or 495:file:`modulename_api.h` in a given C file, not both, otherwise you may get 496conflicting dual definitions. 497 498If the Cython module resides within a package, then: 499 500* The name of the header file contains of the full dotted name of the module. 501* The name of the importing function contains the full name with dots replaced 502 by double underscores. 503 504E.g. a module called :mod:`foo.spam` would have an API header file called 505:file:`foo.spam_api.h` and an importing function called 506:func:`import_foo__spam`. 507 508Multiple public and API declarations 509-------------------------------------- 510 511You can declare a whole group of items as :keyword:`public` and/or 512:keyword:`api` all at once by enclosing them in a :keyword:`cdef` block, for 513example,:: 514 515 cdef public api: 516 void order_spam(int tons) 517 char *get_lunch(float tomato_size) 518 519This can be a useful thing to do in a ``.pxd`` file (see 520:ref:`sharing-declarations`) to make the module's public interface 521available by all three methods. 522 523Acquiring and Releasing the GIL 524--------------------------------- 525 526Cython provides facilities for acquiring and releasing the 527`Global Interpreter Lock (GIL) <http://docs.python.org/dev/glossary.html#term-global-interpreter-lock>`_. 528This may be useful when calling from multi-threaded code into 529(external C) code that may block, or when wanting to use Python 530from a (native) C thread callback. Releasing the GIL should 531obviously only be done for thread-safe code or for code that 532uses other means of protection against race conditions and 533concurrency issues. 534 535Note that acquiring the GIL is a blocking thread-synchronising 536operation, and therefore potentially costly. It might not be 537worth releasing the GIL for minor calculations. Usually, I/O 538operations and substantial computations in parallel code will 539benefit from it. 540 541.. _nogil: 542 543Releasing the GIL 544^^^^^^^^^^^^^^^^^ 545 546You can release the GIL around a section of code using the 547``with nogil`` statement:: 548 549 with nogil: 550 <code to be executed with the GIL released> 551 552Code in the body of the with-statement must not raise exceptions or 553manipulate Python objects in any way, and must not call anything that 554manipulates Python objects without first re-acquiring the GIL. Cython 555validates these operations at compile time, but cannot look into 556external C functions, for example. They must be correctly declared 557as requiring or not requiring the GIL (see below) in order to make 558Cython's checks effective. 559 560.. _gil: 561 562Acquiring the GIL 563^^^^^^^^^^^^^^^^^ 564 565A C function that is to be used as a callback from C code that is executed 566without the GIL needs to acquire the GIL before it can manipulate Python 567objects. This can be done by specifying ``with gil`` in the function 568header:: 569 570 cdef void my_callback(void *data) with gil: 571 ... 572 573If the callback may be called from another non-Python thread, 574care must be taken to initialize the GIL first, through a call to 575`PyEval_InitThreads() <https://docs.python.org/dev/c-api/init.html#c.PyEval_InitThreads>`_. 576If you're already using :ref:`cython.parallel <parallel>` in your module, this will already have been taken care of. 577 578The GIL may also be acquired through the ``with gil`` statement:: 579 580 with gil: 581 <execute this block with the GIL acquired> 582 583Declaring a function as callable without the GIL 584-------------------------------------------------- 585 586You can specify :keyword:`nogil` in a C function header or function type to 587declare that it is safe to call without the GIL.:: 588 589 cdef void my_gil_free_func(int spam) nogil: 590 ... 591 592When you implement such a function in Cython, it cannot have any Python 593arguments or Python object return type. Furthermore, any operation 594that involves Python objects (including calling Python functions) must 595explicitly acquire the GIL first, e.g. by using a ``with gil`` block 596or by calling a function that has been defined ``with gil``. These 597restrictions are checked by Cython and you will get a compile error 598if it finds any Python interaction inside of a ``nogil`` code section. 599 600.. NOTE:: The ``nogil`` function annotation declares that it is safe 601 to call the function without the GIL. It is perfectly allowed 602 to execute it while holding the GIL. The function does not in 603 itself release the GIL if it is held by the caller. 604 605Declaring a function ``with gil`` (i.e. as acquiring the GIL on entry) also 606implicitly makes its signature :keyword:`nogil`. 607