我想要做的是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发布于 2020-03-09 00:39:15
这似乎很好:
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.1秒。奇怪..。
https://stackoverflow.com/questions/60592916
复制相似问题