Host functions and imports
editCreateFunction creates a function whose steps are a .NET callback. Give it to the module as an import:
using var runtime = new WasmRuntime();
var module = runtime.Compile(WasmRuntime.WatToWasm("""
(module
(import "env" "log" (func $log (param i32)))
(func (export "run")
(call $log (i32.const 1))
(call $log (i32.const 2))))
"""));
using var store = runtime.CreateStore();
var logged = new List<int>();
var log = store.CreateFunction(
new WasmFunctionType([WasmValueType.I32], []),
(arguments, results) => logged.Add(arguments[0].I32));
// The imports are resolved by their module and name
var instance = store.Instantiate(module, new WasmImports().Define("env", "log", log));
instance.GetFunction("run")!.Call();
Assert.Equal([1, 2], logged);- WasmImports resolves the imports by their module and name; the Define overload that takes an instance defines all its exports, to link several modules. Instantiate also takes the values in the order of Imports.
- A missing import, or a value whose type does not match the import, throws a WasmLinkException.
- The callback receives one argument per parameter, and writes one result per result of the type. An exception it throws stops the execution and is thrown by the call into WebAssembly, unless it is a WasmThrowException, which throws a WebAssembly exception that the module can catch (see Exceptions and traps).
- The
stateargument is kept by the function, in HostState. - The source generator of the package writes the type and the conversions of a host function from a .NET method marked with WasmImportAttribute: see Typed exports and imports.
The other imports are created by CreateMemory, CreateTable, CreateGlobal and CreateTag, or are the exports of another instance of the same store.
Host values
An externref holds any .NET object: FromHostValue wraps it in a WasmHostReference, and the module gives it back unchanged. The other references are the functions, the structs and the arrays of the GC types (WasmGcObject, whose arrays are read and written with GetArrayElement and SetArrayElement), the i31ref scalars (WasmI31Reference) and the exceptions.