Passing JS function to Emscripten-generated code

前端 未结 5 1526
自闭症患者
自闭症患者 2020-12-29 06:13

I have a piece of C++ code converted to JavaScript via Emscripten. I would like the converted C++ code to call back to the JavaScript code that calls it. Something like:

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 07:14

    I believe the accepted answer is a bit outdated.

    Please refer to this bullet point in the "Interacting with code" emscripten tutorial.

    E.g. C:

    void invoke_function_pointer(void(*f)(void)) {
      (*f)();
    }
    

    JS:

    var pointer = Runtime.addFunction(function() { 
      console.log('I was called from C world!'); 
    });
    Module.ccall('invoke_function_pointer', 'number', ['number'], [pointer]);
    Runtime.removeFunction(pointer);
    

    This way the C-code does not need to be aware of that it is transpiled to JS and any bridges required can purely be controlled from JS.

    (code hacked into message composer; may contain errors)

提交回复
热议问题