Search code examples
pythoncpython-3.xcythoninline

Is there a built-in way to use inline C code in Python?


Even if numba, cython (and especially cython.inline) exist, in some cases, it would be interesting to have inline C code in Python.

Is there a built-in way (in Python standard library) to have inline C code?

PS: scipy.weave used to provide this, but it's Python 2 only.


Solution

  • Directly in the Python standard library, probably not. But it's possible to have something very close to inline C in Python with the cffi module (pip install cffi).

    Here is an example, inspired by this article and this question, showing how to implement a factorial function in Python + "inline" C:

    from cffi import FFI
    ffi = FFI()
    ffi.set_source("_test", """
    long factorial(int n) {
        long r = n;
        while(n > 1) {
            n -= 1;
            r *= n;
        }
        return r;
    }
    """)
    ffi.cdef("""long factorial(int);""")
    ffi.compile()
    from _test import lib     # import the compiled library
    print(lib.factorial(10))  # 3628800
    

    Notes:

    • ffi.set_source(...) defines the actual C source code
    • ffi.cdef(...) is the equivalent of the .h header file
    • you can of course add some cleaning code after, if you don't need the compiled library at the end (however, cython.inline does the same and the compiled .pyd files are not cleaned by default, see here)
    • this quick inline use is particularly useful during a prototyping / development phase. Once everything is ready, you can separate the build (that you do only once), and the rest of the code which imports the pre-compiled library

    It seems too good to be true, but it seems to work!