WebAssembly startup
Preface
Why use WebAssembly?
Just for freestanding and comfortable!
I use zig
, wasmtime
and Web Js
to show the instances.
Startup
Backend
Complier to wasm32-freestanding
zig build-lib main.zig -target wasm32-freestanding --name a -dynamic -rdynamic
target
: Targets
dynamic
: linking dynamic
rdynamic
: export all symbols
export
export fn re() *u8 {
var a = [_:0]c_int{ 1, 2, 3, 4 };
return @ptrCast(&a);
}
export var b = [_]u8{ 1, 2, 3, 4 };
Frontend
Load instance from .wasm
var instance;
WebAssembly.instantiateStreaming(fetch("a.wasm"), {
env: {
print: console.log, // pass the functions/variables
},
})
.then((result) => result.instance)
.then((instance) => {
// pass instance out
window.instance = instance;
});
Exports
instance.exports;
Some useful interface
Get the array from buffer.
docs: Int16Array
new Int8Array([memory.buffer], [Pointer], [len]);
new Int16Array([memory.buffer], [Pointer], [len]);
new Int32Array([memory.buffer], [Pointer], [len]);
examplenew Int16Array(instance.exports.memory.buffer, instance.exports.b, 4);
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 静谧之园!