任务是调用 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;
}
如何链接 smth_that_calls_my_fn
和 my_js_fn
?
最佳答案
您正在寻找的魔法非常简单 - 您需要使用 EM_ASM_ARGS 宏。
具体来说,它看起来像
int smth_that_calls_my_fn(int i, int max) {
EM_ASM_ARGS({ my_js_fn($0, $1); }, i, max);
}
确保您 #include <emscripten.h>
在您的 C 文件中,以便该宏存在。
EM_ASM_ARGS 宏将 JavaScript 代码(在大括号中)作为第一个参数,然后是您要传入的任何其他参数。在 JS 代码中,$0 是第一个参数,$1 是下一个参数,依此类推。
如果您想了解更多信息,我刚刚写了一篇博客文章,详细介绍了该主题:http://devosoft.org/an-introduction-to-web-development-with-emscripten/
关于使用 Emscripten 在 C 代码中回调 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31830024/