Example #1
0

def handle_band(width: int) -> int:
    print('got a line of:', width)
    assert width == 7
    return 0


def mode_parsed(mode: int) -> int:
    print('mode selected:', mode)
    assert mode == 1
    return 0


# load wasm engine
store = Store(engine.JIT(Compiler))
module = Module(store, open('./decoder.wasm', 'rb').read())
import_object = ImportObject()
import_object.register(
    "env", {
        "handle_band": Function(store, handle_band),
        'mode_parsed': Function(store, mode_parsed),
    })
instance = Instance(module, import_object)
mem = instance.exports.memory.int8_view()
chunk_address = instance.exports.get_chunk_address()

# load test data
mem[chunk_address:] = TEST

# run
      (type $sum_t (func (param i32 i32) (result i32)))
      (func $sum_f (type $sum_t) (param $x i32) (param $y i32) (result i32)
        local.get $x
        local.get $y
        i32.add)
      (export "sum" (func $sum_f)))
    """)

# Define the engine that will drive everything.
#
# In this case, the engine is `wasmer.engine.JIT` which roughly
# means that the executable code will live in memory.
#
# This is _the_ place to pass the compiler. Note that `Compiler` is
# not instantiated, we pass the class only.
engine = engine.JIT(Compiler)

# Create a store, that holds the engine.
store = Store(engine)

# Let's compile the Wasm module with the Singlepass compiler.
module = Module(store, wasm_bytes)

# Let's instantiate the Wasm module.
instance = Instance(module)

# Let's call the `sum` exported function.
sum = instance.exports.sum
results = sum(1, 2)

print(results)