PythoC: A new way to generate C code from Python


from pythoc import compile, i32, ptr, i8
from pythoc.libc.stdio import printf

@compile
def add(x: i32, y: i32) -> i32:
    return x + y

@compile
def main(argc: i32, argv: ptr[ptr[i8]]) -> i32:
    printf("%u\n", add(10, 20))

if __name__ == "__main__":
    from pythoc import compile_to_executable
    compile_to_executable()

The first thing you’ll probably notice is the block at the bottom. The compile_to_executable() function is exactly what it sounds like. Call it, and the current module is compiled to an executable of the same name, with all the @compile-decorated functions included.

Another difference is that the main() function now has the same signature as the main() function in a C program. This means the compiled executable will automatically use that as its entry point.

Finally, when you run this program, the generated executable (which shows up in a build subdirectory) doesn’t run automatically; you have to run it yourself. The aim here is to build a standalone C program, indistinguishable from one you wrote by hand in C, but using Python’s syntax.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here