Hello,
I am trying to import a WebAssembly.Global from JavaScript into my Zig-compiled Wasm module.
Based on the MDN documentation, the host (JavaScript) side is straightforward:
const startOffsetGlobal = new WebAssembly.Global({ value: 'i32', mutable: false }, 0);
const endOffsetGlobal = new WebAssembly.Global({ value: 'i32', mutable: false }, 10000);
const importObject = {
env: {
memory: wasm_memory,
array_scope_offset_start: startOffsetGlobal,
array_scope_offset_end: endOffsetGlobal,
},
};
const { instance } = await WebAssembly.instantiate(module, importObject);
The goal is to write Zig code that generates the corresponding Wasm import section:
(module
(import "env" "array_scope_offset_start" (global i32))
(import "env" "array_scope_offset_end" (global i32))
...
)
And then uses the global.get instruction to access these values.
However, I have been unable to find the correct Zig syntax to achieve this.
I have tried this:
// main.zig
extern const array_scope_offset_start: usize;
extern const array_scope_offset_end: usize;
// build.zig
// ...
exe.import_symbols = true;
// ...
This did not work. The compilation succeeded, but it produced a faulty Wasm module. Instead of creating global imports, the compiler treated the symbols as being located at memory address 0. The generated WAT for using the global was i32.const 0, i32.load, which is incorrect.
Given the above, what is the correct, idiomatic Zig syntax to declare an external global variable that will be imported from a WebAssembly host module (e.g., āenvā)?
Thank you for your help.