You need to define the JavaScript function you passed into importObj.env within the C/C++ code that utilizes it. The function signature must match what you passed in. The following example demonstrates this in greater detail. Here's the JavaScript code that interacts with the compiled C file (index.html):
// index.html <script> contents
const env = {
_logAndMultiplyTwoNums: (num1, num2) => {
const result = num1 * num2;
console.log(result);
return result;
},
};
loadWasm('main.wasm', { env })
.then(({ instance }) => {
const result = instance.exports._callMultiply(5.5, 10);
console.log(result);
// 55 is logged to the console twice
});
This is the contents of main.c, which is compiled to main.wasm and used within index.html:
// main.c (compiled to main.wasm)
extern float logAndMultiplyTwoNums(float num1, float num2);
float callMultiply(float num1, float num2) {
return logAndMultiplyTwoNums(num1, num2);
}
You call the JavaScript function in your C/C++ the same way you'd call a normal C/C++ function. Although you prefix your function with a _ when you pass it into the importObj.env, you don't need to include the prefix when defining it in the C/C++ file.