Virtual Machines and Interpreted Language
In order to run code, we sometimes need to compile it. Some are compiled into machine code (C, Go), others are compiled into a bytecode format (Java, Python).
Today, we look into some of these and how code from these languages actually runs on your CPU.
Python Bytecode ๐︎
When you run Python code, it is first compiled into bytecode, and then run directly on the CPU by the interpreter.
These operations are done by whichever Python installation you have, for example
- CPython : the standard (coded in C)
- Jython : for scripting Java apps (Java VM)
- IronPython : for scripting C#/.Net apps (.Net VM)
- PyPy : CPython for speed (JIT)
Interestingly, Python code can also be compiled directly into machine code using Cython .
Java? ๐︎
People would describe Java as a compiled language because you need to explicitly compile it before running it. However, it does also have a virtual machine.
Why Virtual Machines ๐︎
Virtual machines are beneficial because we do not need to worry about compiling code to run in a specific environment.
If I compile Java code, I can run my Java anywhere there is a JVM. This is the same with Python.
In C, I need to compile my code to run on specific architectures. Since the systems call available on each architecture may vary, running compiled C code on one machine might not run on another.
Foreign Function Interface ๐︎
Another question I had was this. How can we run other languages code, eg Rust, in Python? This seemed quite common, but how does this actually work?
I found a great blog post on this here .
Essentially, to glue these languages together, there is this thing called FFI, the foreign function interface .
It allows Python to run C functions, and for Rust to export as C functions.