我正在尝试做的是具有给定要求的WASM加载程序:
此作品:
let testWASM;
(async() => {
const config = {
env: {
__memory_base: 0,
__table_base: 0,
memory: new WebAssembly.Memory({
initial: 256,
}),
table: new WebAssembly.Table({
initial: 0,
element: 'anyfunc',
}),
}
}
const fetchPromise = fetch(process.env.PUBLIC_URL + '/hello.wasm');
const {instance} = await WebAssembly.instantiateStreaming(fetchPromise, config);
testWASM = instance.exports.fib;
console.log(testWASM());
})();
setTimeout(() => {
console.log(testWASM());
}, 2000)
显然setTimeout是非常糟糕的方法。
编辑:hello.c:
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int fib() {
return 42;
}
构建命令:
emcc hello.c -Os -s WASM=1 -s SIDE_MODULE=1 -o hello.wasm
编辑:
这在导出方面效果很好,但我认为它不满足第一个要求。这非常慢,我认为这是由于每次调用函数时都会获取:
wasm.js
module.exports = async () => {
const config = {
env: {
__memory_base: 0,
__table_base: 0,
memory: new WebAssembly.Memory({
initial: 256
}),
table: new WebAssembly.Table({
initial: 0,
element: "anyfunc"
})
}
};
const fetchPromise = fetch(process.env.PUBLIC_URL + "/hello.wasm");
const { instance } = await WebAssembly.instantiateStreaming(
fetchPromise,
config
);
return instance.exports.fib();
};
然后我们可以如下使用它:
import * as foo from './wasm.js'
const bar = async () => {
console.log(await foo())
}
bar(); //42
这似乎很好用:
let cache;
module.exports = async (x, y, z) => {
if (cache) {
return cache(x, y, z);
} else {
const config = {
env: {
__memory_base: 0,
__table_base: 0,
memory: new WebAssembly.Memory({
initial: 256
}),
table: new WebAssembly.Table({
initial: 0,
element: "anyfunc"
})
}
};
const fetchPromise = fetch(process.env.PUBLIC_URL + "/hello.wasm");
const { instance } = await WebAssembly.instantiateStreaming(
fetchPromise,
config
);
cache = instance.exports.mandelIter;
return instance.exports.mandelIter(x, y, z);
}
};
但是由于某种原因,它的延迟时间比普通JS函数大约0.1s。奇怪...