Binaryen.py is a python wrapper for Binaryen. Use this to create, optimise and interpret WebAssembly binaries in python.
Install through PyPI.
pip install binaryen.py
Windows, Mac (Intel & ARM) and Linux (manylinux, musllinux) are supported.
- (If upgrading binaryen version) Update
BINARYEN_VERSIONinpyproject.tomland.github/workflows/build.yaml - Run
bash scripts/build_libbinaryen.sh - Run
python -m pip install -e .,cibuildwheel,python -m pip wheel ., or whichever supported build command you would prefer
import binaryen from binaryen.type import Int32, TypeNone # Equivalent python function def add(x, y): return x + y mod = binaryen.Module() mod.add_function( b"add", binaryen.type.create([Int32, Int32]), Int32, [Int32], mod.block( None, [ mod.local_set( 2, mod.binary( binaryen.operations.AddInt32(), mod.local_get(0, Int32), mod.local_get(1, Int32), ), ), mod.Return(mod.local_get(2, Int32)), ], TypeNone, ), ) if not mod.validate(): raise RuntimeError("Invalid module!") mod.add_function_export(b"add", b"add") mod.optimize() mod.print()
Results in the following Wasm
(module (type 0ドル (func (param i32 i32) (result i32))) (export "add" (func $add)) (func $add (; has Stack IR ;) (param 0ドル i32) (param 1ドル i32) (result i32) (i32.add (local.get 0ドル) (local.get 1ドル) ) ) )
Reference the Binaryen header file to understand how to use Binaryen. This package makes no significant changes to how Binaryen is used. The majority of the work this module does is interoperating between C and Python and creating more pythonic classes for Modules, Expressions and Functions.
For more examples see examples.
You can still call any missing functions that haven't been implemented by the wrapper yet by calling them directly. To do this use binaryen.lib.BinaryenFullFunctionName() and call the full function name as described in the Binaryen header file.