C in Python

Cinpy - C in Python

Related projects

Valid HTML 4.01 Transitional


Cinpy is a Python library that allows you to implement functions with C in Python modules. Inlined C code is compiled with tcc (Tiny C Compiler) at runtime. The results are made callable in Python with ctypes library.

There are also other projects that already can do this stuff, and probably much more (see the bottom of the page). The reasons for the existence of cinpy are

  • simplicity of usage: modules that include C code do not seem to require any special treatment (preprocessing, compiling, etc.). C code is compiled quietly under the hood whenever C is used in function definition.
  • simplicity of implementation: no more than 20 lines of code are needed to do the trick, once you use ctypes and know where libtcc.so is located.
  • the needed compiler is tiny and it runs fast and completely in memory (no write access to any other media is required).


The following code is ripped from cinpy_test.py included in the package.
import ctypes
import cinpy

# Fibonacci in Python
def fibpy(x):
    if x<=1: return 1
    return fibpy(x-1)+fibpy(x-2)

# Fibonacci in C
                long fib(int x) {
                    if (x<=1) return 1;
                    return fib(x-1)+fib(x-2);

# ...and then just use them...
# (there _is_ a difference in the performance)
print fibpy(30)
print fibc(30)




Cinpy is distributed under LGPL.


You can find interesting benchmark results in Amund Tveit's blog.

Related projects

  • Weave is much more complete C/C++-in-Python package.
  • PyInline uses the compiler in distutils, just like Weave does.
    Not that closely related projects: (No more inlining C/C++, but compiling Python to native/C/C++)
  • If you do not want to write C but still would like to compile some Python functions to native code, use Psyco.
  • There is also a Python to C++ compiler in early stage of development (link added 8 Dec 2006).


I'd like to thank Pablo Virolainen for this GREAT idea.
Antti Kervinen email: ask@cs.tut.fi
Back to my homepage
Last modified: Sat Sep 8 22:00:00 EEST 2007