Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 781
Basj Avatar asked May 23 '26 16:05

Basj


1 Answers

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!

like image 130
Basj Avatar answered May 26 '26 06:05

Basj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!