Calling JavaScript functions as function pointers from C
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 toaddFunction
will be called.See test_add_function in tests/test_core.py for an example.
You should build with
-s ALLOW_TABLE_GROWTH
to allow new functions to be added to the table. Otherwise by default the table has a fixed size.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 typeFor 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.
可以使用addFunction返回一个表示函数指针的整数值。将该整数传递给C代码,然后让它将该值作为函数指针调用,然后调用发送到addFunction的JavaScript函数。
在LLVM wasm后端使用addFunction时, 需要提供另一个参数wasm函数签名字符串。签名字符串中的 每个字符代表一种类型。 第一个字符表示函数的返回类型, 其余字符表示参数类型。
Module.addFunction(()=>{
}, "sig");
回调函数参数类型:
typedef void (*VideoCallbackN)(unsigned char *data_y, unsigned char *data_u, unsigned char *data_v, int line1, int line2, int line3, int width, int height, long pts);
sig:'viiiiiiiid' —— 错误的!
sig:'viiiiiiiii' —— 正确的!
——记一次耗时的debug过程
https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html#