参考文章走近 WebAssembly 之调试大法调试wasm过程中有些错误,这里记录一下,可能是作者使用的emsdk版本太低导致
参考文章Cannot instantiate WebAssembly #11 So I found out the reason. With later version of emcc replace memoryBase with __memory_base and tableBase with __table_base 修改debug.html 如下:
<html>
<head>
<script>
// 下面这些配置是作为wasm初始化用的,去掉某一个会报错。
const importObj = {
env: {
'memory': new WebAssembly.Memory({initial: 256, maximum: 256}),
'__memory_base': 0,
'tableBase': 0,
'table': new WebAssembly.Table({initial: 10, element: 'anyfunc'}),
abort:alert
}
};
// 直接使用 WebAssembly.instantiateStream的方式会报错,说是 debug.wasm 资源不是 application/wasm 格式s.
fetch('./debug.wasm').then(response =>
response.arrayBuffer()
).then(bytes => WebAssembly.instantiate(bytes,importObj)).then(results => {
instance = results.instance;
var sumOfSquare= instance.exports._sumOfSquare; //注意这里导出的方法名前有下划线!!
var button = document.getElementById('run');
button.addEventListener('click', function() {
var input1 = 3;
var input2 = 4;
alert('sumOfSquare('+input1+','+input2+')='+sumOfSquare(input1,input2));
}, false);
});
</script>
</head>
<body>
<input type="button" id="run" value="click"/>
</body>
</html>
at HTMLInputElement.<anonymous> (debug.htm:26)
这里说找不到导出的函数sumOfSquare,反编译wasm看:
wasm2wat debug.wasm
显示:
(module
(type (;0;) (func))
(import "env" "__memory_base" (global (;0;) i32))
(func (;0;) (type 0)
global.get 0
global.set 1
global.get 1
i32.const 5242880
i32.add
global.set 2)
(global (;1;) (mut i32) (i32.const 0))
(global (;2;) (mut i32) (i32.const 0))
(export "__post_instantiate" (func 0)))
确实没有导出函数sumOfSquare,参考文章编译 C/C++ 为 WebAssembly 默认情况下,Emscripten 生成的代码只会调用 main() 函数,其它的函数将被视为无用代码。在一个函数名之前添加 EMSCRIPTEN_KEEPALIVE 能够防止这样的事情发生。你需要导入 emscripten.h 库来使用 EMSCRIPTEN_KEEPALIVE。 修改debug.c:
#include <emscripten/emscripten.h>
int EMSCRIPTEN_KEEPALIVE sumOfSquare(int a,int b){
int t1=a*a;
int t2=b*b;
return t1+t2;
}
这个实在没办法,chrome和Firefox都不行