Home > Back-end >  WASM&C: Cant find function
WASM&C: Cant find function

Time:02-19

File hierarchy:

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);

error:

TypeError: instance.exports.power is not a function

Just started wasm & can't figure out why the power function is not visible

CodePudding user response:

How are you compiling your C to wasm BTW?

In general its not enough to simply set the visibility. You either need to pass --export=power to the linker (most likely via -Wl,--export=power passed to the compiler), or set the 'export_name' attribute: __attribute__((export_name("power")))

  • Related