You can use addFunction
to return an integer value that represents a function pointer. Passing that integer to C code then lets it call that value as a function pointer, and the JavaScript function you sent to addFunction
will be called.
See test_add_function in tests/test_core.py for an example.
When using addFunction
, there is a backing array where these functions are stored. This array must be explicitly sized, which can be done via a compile-time setting, RESERVED_FUNCTION_POINTERS
. For example, to reserve space for 20 functions to be added:
emcc ... -s RESERVED_FUNCTION_POINTERS=20 ...
Note
When using addFunction
on LLVM wasm backend, you need to provide an additional second argument, a Wasm function signature string. Each character within a signature string represents a type. The first character represents the return type of a function, and remaining characters are for parameter types.
'v'
: void type'i'
: 32-bit integer type'j'
: 64-bit integer type (currently does not exist in JavaScript)'f'
: 32-bit float type'd'
: 64-bit float type
For example, if you add a function that takes an integer and does not return anything, you can do addFunction(your_function, 'vi');
. See tests/interop/test_add_function_post.js for an example.
https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#calling-javascript-functions-as-function-pointers-from-c