当使用 new WebAssembly.Instance(module) 实例化 WebAssembly 模块时,确保在 C 文件中定义的函数已经被导出。在 C 文件中,可以使用 EMSCRIPTEN_KEEPALIVE 宏将函数标记为导出。
例如,在 C 文件中声明一个加法函数,并通过 EMSCRIPTEN_KEEPALIVE 导出:
#include <emscripten.h>
EMSCRIPTEN_KEEPALIVE
int add(int a, int b) {
return a + b;
}
然后,通过编译器将其转换为 WebAssembly 模块:
emcc your_c_file.c -o output.wasm -s EXPORTED_FUNCTIONS='["_add"]'
在这里,我们使用 -s EXPORTED_FUNCTIONS='["_add"]' 选项来指定要导出的函数。确保在这个列表中包含你想要使用的所有函数。
最后,在前端代码中实例化模块并调用导出的函数:
fetch('output.wasm')
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.instantiate(buffer))
.then(result => {
const instance = result.instance;
const add = instance.exports._add; // 注意此处的命名规则
const sum = add(2, 3);
console.log(sum); // 输出结果:5
});
请注意,WebAssembly 函数的命名规则可能会稍有不同,需要根据具体情况进行调整。
内容由零声教学AI助手提供,问题来源于学员提问




