WASM&C:找不到函数
WASM&C: Cant find function
文件层次结构:
src:
main.c
main.html
main.js
out:
main.wasm -> compiled file
main.c:
#define WASM_EXPORT __attribute__((visibility("default")))
WASM_EXPORT
float power(float number,float power){
float res = number;
for (int i = 0; i < power - 1 ; i++) {
res = res * number;
}
return res;
}
main.js:
fetch('../out/main.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes)
).then(results => {
instance = results.instance;
document.getElementById("container").textContent = instance.exports.power(2,8);
}).catch(console.error);
错误:
TypeError: instance.exports.power is not a function
刚开始使用 wasm,无法弄清楚为什么 power 函数不可见
顺便说一句,您如何将 C 语言编译为 wasm?
一般来说,仅仅设置可见性是不够的。您需要将 --export=power
传递给链接器(很可能是通过 -Wl,--export=power
传递给编译器),或者设置 'export_name' 属性:__attribute__((export_name("power")))
文件层次结构:
src:
main.c
main.html
main.js
out:
main.wasm -> compiled file
main.c:
#define WASM_EXPORT __attribute__((visibility("default")))
WASM_EXPORT
float power(float number,float power){
float res = number;
for (int i = 0; i < power - 1 ; i++) {
res = res * number;
}
return res;
}
main.js:
fetch('../out/main.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes)
).then(results => {
instance = results.instance;
document.getElementById("container").textContent = instance.exports.power(2,8);
}).catch(console.error);
错误:
TypeError: instance.exports.power is not a function
刚开始使用 wasm,无法弄清楚为什么 power 函数不可见
顺便说一句,您如何将 C 语言编译为 wasm?
一般来说,仅仅设置可见性是不够的。您需要将 --export=power
传递给链接器(很可能是通过 -Wl,--export=power
传递给编译器),或者设置 'export_name' 属性:__attribute__((export_name("power")))