[英]LinkError: WebAssembly.instantiate() function import requires a callable
[英]WebAssembly LinkError: function import requires a callable
我最近开始使用 WebAssembly。 尝试在我的 C 代码中使用日志时遇到问题。 我以最简单的方式重新创建了错误。 我得到的错误是
Uncaught (in promise) LinkError: WebAssembly.Instance(): Import #1 module="env" function="_log" error: function import requires a callable
错误指向这个 function,特别是WebAsembly.Instance(module, imports)
function loadWebAssembly(filename, imports = {}) {
return fetch(filename)
.then((response) => response.arrayBuffer())
.then((buffer) => WebAssembly.compile(buffer))
.then((module) => {
imports.env = imports.env || {}
Object.assign(imports.env, {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({
initial: 256,
maximum: 512,
}),
table: new WebAssembly.Table({
initial: 0,
maximum: 0,
element: 'anyfunc',
}),
})
return new WebAssembly.Instance(module, imports)
})
}
(我用loadWebAssembly('/test.wasm')
将此称为 function )
我的 C 代码是
#include <math.h>
double test(v) {
return log(v)
}
编译时没有错误
emcc test.c -Os -s WASM=1 -s SIDE_MODULE=1 -o test.wasm
我一直无法修复这个错误,我希望有人能帮助我。
您没有在imports.env
提供log()
的实现
Object.assign(imports.env, {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({
initial: 256,
maximum: 512,
}),
table: new WebAssembly.Table({
initial: 0,
maximum: 0,
element: 'anyfunc',
}),
_log: Math.log,
})
我可能错了,但我认为您的 C 代码是错误的
默认情况下,emscripten 仅导出main
function 其他为死代码
您需要使用宏EMSCRIPTEN_KEEPALIVE
告诉emscripten
保持test
function
并且不要忘记包含 header 文件emscripten/emscripten.h
有关更多信息 go 到此链接
#include <stdio.h>
#include <emscripten/emscripten.h>
#include <math.h>
EMSCRIPTEN_KEEPALIVE
double test(double x)
{
return log(x);
}
您可以在 js 中访问您的 function
loadWebAssembly('test.wasm')
.then((data) => {
console.log(data.exports) // {__wasm_call_ctors: ƒ, log10: ƒ}
}).
catch((err) => {
console.log(err);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.