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

Vya*_*lav 2 javascript c callback emscripten

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

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

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;
    }
Run Code Online (Sandbox Code Playgroud)

我如何链接smth_that_calls_my_fnmy_js_fn

Cha*_*ria 5

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

具体来说,它可以看起来像

int smth_that_calls_my_fn(int i, int max) {
  EM_ASM_ARGS({ my_js_fn($0, $1); }, i, max);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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