js代码
<script>
/**
* @param {String} path wasm 文件路径
* @param {Object} imports 传递到 wasm 代码中的变量
*/
function loadWebAssembly (path, imports = {}) {
return fetch(path) // 加载文件
.then(response => response.arrayBuffer()) // 转成 ArrayBuffer
.then(buffer => WebAssembly.compile(buffer))
.then(module => {
imports.env = imports.env || {}
// 开辟内存空间
imports.env.memoryBase = imports.env.memoryBase || 0
if (!imports.env.memory) {
imports.env.memory = new WebAssembly.Memory({ initial: 256 })
}
// 创建变量映射表
imports.env.tableBase = imports.env.tableBase || 0
if (!imports.env.table) {
// 在 MVP 版本中 element 只能是 "anyfunc"
imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' })
}
// 创建 WebAssembly 实例
return new WebAssembly.Instance(module, imports)
})
}
//调用
loadWebAssembly('test.wasm')
.then(instance => {
console.log(instance)
const add = instance.exports._Z3addii//取出c里面的方法
const square = instance.exports._Z6squarei//取出c里面的方法
console.log('10 + 20 =', add(10, 20))
console.log('3*3 =', square(3))
console.log('(2 + 5)*2 =', square(add(2 + 5)))
})
</script>
可以把c/c++文件编译成wasm文件,使用emscripten编译
可以在控制台打印一下获取到你想要的方法