I wrote the below file:
const std = @import("std");
pub export fn add(a: i32, b: i32) i32 {
std.debug.print("add({}, {}) = {}\n", .{ a, b, a + b });
return a + b;
}
pub fn main() void {
std.debug.print("Hello there from Zig!\n", .{});
const x = add(2, 2);
std.debug.print("The returned result is: {}\n", .{x});
}
And compiled it as:
zig build-exe -O ReleaseSmall -target wasm32-wasi main.zig
Tried to execute it using wasmedge
I got the below error:
PS C:\Users\hasan> wasmedge --reactor main.wasm add 2 2
[2023-07-14 16:04:54.494] [error] wasmedge runtime failed: wasm function not found, Code: 0x05
[2023-07-14 16:04:54.495] [error] When executing function name: "add"
I tried another approach through nodejs, but looks the same, only the main
AKA _start()
function is only exported, I wrote:
import { readFile } from 'node:fs/promises';
import { WASI } from 'wasi';
import { argv, env } from 'node:process';
const wasi = new WASI({
version: 'preview1',
args: argv,
env,
preopens: {
'/sandbox': './',
},
});
const wasm = await WebAssembly.compile(
await readFile(new URL('./main.wasm', import.meta.url)),
);
const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
wasi.start(instance);
console.log(instance.exports);
const result = instance.exports.add(3, 4);
console.log(result); // 7
and got:
Hello there from Zig!
add(2, 2) = 4
The returned result is: 4
[Object: null prototype] {
memory: Memory [WebAssembly.Memory] {},
_start: [Function: 2]
}
file:///C:/Users/hasan/wa-gpt/callwasm.js:23
const result = instance.exports.add(3, 4);
^
TypeError: instance.exports.add is not a function
at file:///C:/Users/hasan/wa-gpt/callwasm.js:23:33
Node.js v20.4.0