Wasmer Cranelift Compiler
The `wasmer-compiler-cranelift` library provides the Cranelift compiler backend for the `wasmer` Python package, enabling the compilation of WebAssembly (Wasm) modules. Cranelift is known for its balanced approach, offering faster compilation times compared to LLVM, moderate runtime performance, and enhanced security against malicious Wasm input. The current Python package version is `1.1.0` (released Jan 2022), though the underlying Wasmer runtime frequently updates, with Wasmer 7.0 (Jan 2026) featuring an upgraded Cranelift backend and new capabilities for Python integration.
Warnings
- breaking The `wasmer-python` API, including how compilers are used, underwent significant changes with the `1.0.0` release to better align with the Wasmer C API. Code written for `0.x` versions will likely break.
- gotcha `wasmer-compiler-cranelift` is a companion package and requires the `wasmer` package to be installed alongside it to function correctly. It is not a standalone runtime.
- gotcha While Cranelift offers faster compilation, the `wasmer-compiler-llvm` backend typically provides approximately 50% better runtime performance for production environments where execution speed is critical. Choose the compiler based on your specific needs (fast compilation vs. fast execution).
- gotcha If a pre-compiled binary wheel for `wasmer` (and its compilers) is not available for your specific system or Python version, a fallback pure-Python wheel might be installed. This can lead to an `ImportError` at runtime with the message 'Wasmer is not available on this system'.
Install
-
pip install wasmer wasmer-compiler-cranelift
Imports
- Compiler
from wasmer_compiler_cranelift import Compiler
- Store
from wasmer import Store
- Module
from wasmer import Module
- Instance
from wasmer import Instance
- engine
from wasmer import engine
- wat2wasm
from wasmer import wat2wasm
Quickstart
from wasmer import Store, Module, Instance, engine, wat2wasm
from wasmer_compiler_cranelift import Compiler
# 1. Create a Store with the Cranelift compiler
# You can choose between JIT (Just-In-Time) or Native engine.
# JIT is good for development and dynamic compilation.
store = Store(engine.JIT(Compiler))
# 2. Define a WebAssembly module in WebAssembly Text Format (WAT)
wasm_bytes = wat2wasm(
"""
(module
(type (func (param i32 i32) (result i32)))
(func (export "sum") (type 0) (param i32) (param i32) (result i32)
local.get 0
local.get 1
i32.add
)
)
"""
)
# 3. Compile the Wasm module
module = Module(store, wasm_bytes)
# 4. Instantiate the module
instance = Instance(module)
# 5. Call an exported function
result = instance.exports.sum(5, 37)
print(f"Result of sum(5, 37): {result}") # Expected: 42