javascript 使用 Emscripten 在 C 代码中进行函数回调

javascript function callback in C code using Emscripten

任务是调用一个javascript函数作为回调,以显示while循环操作的进度。 例如。 JS:

var my_js_fn = function(curstate, maxstate){//int variables
console.log(curstate.toString() + " of " + maxstate.toString());
}

C伪代码:

int smth_that_calls_my_fn(int i, int max) {
/*
the_magic to call my_js_fn()
*/
}
    int main(){
    //....
        while (i < max){
        smth_that_calls_my_fn(i,max);
        }
    //....
    return 0;
    }

我怎样才能 link smth_that_calls_my_fnmy_js_fn

您正在寻找的魔法非常简单——您需要使用 EM_ASM_ARGS 宏。

具体来说,可以像

int smth_that_calls_my_fn(int i, int max) {
  EM_ASM_ARGS({ my_js_fn([=10=], ); }, i, max);
}

确保您在 C 文件中 #include <emscripten.h> 以便此宏存在。

EM_ASM_ARGS宏将JavaScript代码(大括号内)作为第一个参数,然后是你想传入的任何其他参数。在JS代码中,$0是第一个参数跟随,下一个 $1,依此类推。

我刚刚写了一篇博客文章,详细介绍了这个主题,如果您想了解更多信息:http://devosoft.org/an-introduction-to-web-development-with-emscripten/