|
| 1 | +# python-tinycc |
| 2 | + |
| 3 | +Module to use the Tiny C Compiler for inline C in Python. |
| 4 | +Tested with Ubuntu 14 (x86_64), WinXP (x86) and Raspbian (Raspberry Pi 3, ARMv7). |
| 5 | + |
| 6 | + |
| 7 | +### Get the Tiny C Compiler |
| 8 | + |
| 9 | +#### Linux |
| 10 | +Run the following commands: |
| 11 | +```bash |
| 12 | +cd <modulepath> |
| 13 | +git clone git://repo.or.cz/tinycc.git |
| 14 | +mkdir build |
| 15 | +cd build |
| 16 | +../tinycc/configure --prefix=../linux --with-libgcc --disable-static |
| 17 | +make all |
| 18 | +make install |
| 19 | +``` |
| 20 | + |
| 21 | +#### Windows |
| 22 | + |
| 23 | +For Windows the repo contains a binary version (x86 only). |
| 24 | +It was build from source with MinGW: |
| 25 | +```bash |
| 26 | +cd <modulepath> |
| 27 | +git clone git://repo.or.cz/tinycc.git |
| 28 | +mkdir build |
| 29 | +cd build |
| 30 | +../tinycc/configure --prefix=../win32 --disable-static --extra-ldflags=-static-libgcc |
| 31 | +make all |
| 32 | +make install |
| 33 | +``` |
| 34 | + |
| 35 | +### Examples |
| 36 | +A simple example with the 'run' state: |
| 37 | +```python |
| 38 | +>>> from tinycc import TinyCC |
| 39 | +>>> c_code = '#include <stdio.h>' |
| 40 | +>>> c_code += 'void main(void) {' |
| 41 | +>>> c_code += ' printf("Hello World!\n");' |
| 42 | +>>> c_code += '}' |
| 43 | +>>> state = TinyCC().create_state('run') |
| 44 | +>>> state.compile(c_code) |
| 45 | +>>> state.run([]) |
| 46 | +``` |
| 47 | + |
| 48 | +Example with inline code: |
| 49 | +```python |
| 50 | +>>> from tinycc import TinyCC, InlineGenerator |
| 51 | +>>> from ctypes import c_int |
| 52 | +>>> |
| 53 | +>>> gen = InlineGenerator() |
| 54 | +>>> |
| 55 | +>>> # C function to be used from Python |
| 56 | +... @gen.c_function(c_int, c_int, c_int, c_int) |
| 57 | +... def add_mul(a, b, c): |
| 58 | +... "return mul(a + b, c);" # calls the Python function mul |
| 59 | +... |
| 60 | +>>> # Python function to be used from C |
| 61 | +... @gen.callable_function(c_int, c_int, c_int) |
| 62 | +... def mul(a, b): |
| 63 | +... return a * b |
| 64 | +... |
| 65 | +>>> # compile the code |
| 66 | +... state = TinyCC().create_state() |
| 67 | +>>> state.compile(gen.code) |
| 68 | +>>> state.relocate() |
| 69 | +>>> |
| 70 | +>>> # bind to state for symbol resolution |
| 71 | +... gen.bind_state(state) |
| 72 | +>>> |
| 73 | +>>> # use it |
| 74 | +... add_mul(23, 42, 7) |
| 75 | +455 |
| 76 | +``` |
| 77 | +See the example files for more usage ideas. |
| 78 | + |
| 79 | +### TODO |
| 80 | +* Testing |
| 81 | +* Python 3 support |
| 82 | +* PyPI package |
0 commit comments