Embedding Cython modules in C/C++ applications

This is a stub documentation page. PRs very welcome.

Quick links:

Initialising your main module

Most importantly, DO NOT call the module init function instead of importing the module. This is not the right way to initialise an extension module. (It was always wrong but used to work before, but since Python 3.5, it is wrong and no longer works.)

For details, see the documentation of the module init function in CPython and PEP 489 regarding the module initialisation mechanism in CPython 3.5 and later.

The PyImport_AppendInittab() function in CPython allows registering statically (or dynamically) linked extension modules for later imports. An example is given in the documentation of the module init function that is linked above.

Embedding example code

The following is a simple example that shows the main steps for embedding a Cython module (embedded.pyx) in Python 3.x.

First, here is a Cython module that exports a C function to be called by external code. Note that the say_hello_from_python() function is declared as public to export it as a linker symbol that can be used by other C files, which in this case is embedded_main.c.

# embedded.pyx

# The following two lines are for test purposed only, please ignore them.
# distutils: sources = embedded_main.c
# tag: py3only

TEXT_TO_SAY = 'Hello from Python!'

cdef public int say_hello_from_python() except -1:
    print(TEXT_TO_SAY)
    return 0

The C main() function of your program could look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* embedded_main.c */

/* This include file is automatically generated by Cython for 'public' functions. */
#include "embedded.h"

#ifdef __cplusplus
extern "C" {
#endif

int
main(int argc, char *argv[])
{
    PyObject *pmodule;
    wchar_t *program;

    program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0], got %d arguments\n", argc);
        exit(1);
    }

    /* Add a built-in module, before Py_Initialize */
    if (PyImport_AppendInittab("embedded", PyInit_embedded) == -1) {
        fprintf(stderr, "Error: could not extend in-built modules table\n");
        exit(1);
    }

    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(program);

    /* Initialize the Python interpreter.  Required.
       If this step fails, it will be a fatal error. */
    Py_Initialize();

    /* Optionally import the module; alternatively,
       import can be deferred until the embedded script
       imports it. */
    pmodule = PyImport_ImportModule("embedded");
    if (!pmodule) {
        PyErr_Print();
        fprintf(stderr, "Error: could not import module 'embedded'\n");
        goto exit_with_error;
    }

    /* Now call into your module code. */
    if (say_hello_from_python() < 0) {
        PyErr_Print();
        fprintf(stderr, "Error in Python code, exception was printed.\n");
        goto exit_with_error;
    }

    /* ... */

    /* Clean up after using CPython. */
    PyMem_RawFree(program);
    Py_Finalize();

    return 0;

    /* Clean up in the error cases above. */
exit_with_error:
    PyMem_RawFree(program);
    Py_Finalize();
    return 1;
}

#ifdef __cplusplus
}
#endif

(Adapted from the CPython documentation.)

Instead of writing such a main() function yourself, you can also let Cython generate one into your module’s C file with the cython --embed option. Or use the cython_freeze script to embed multiple modules. See the embedding demo program for a complete example setup.