Passing JS function to Emscripten-generated code

前端 未结 5 1524
自闭症患者
自闭症患者 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 06:57

    I needed to write something very similar to what is described in the question. My code ended up looking like this:

    C:

    void call(void (*back)(char*)){
        back("Hello!");
    }
    

    JS:

    function back(text){
        alert(Pointer_stringify(text));
    }
    var pointer = Runtime.addFunction(back);
    var call = Module.cwrap('call', 'void', ['pointer']);
    call(pointer);
    Runtime.removeFunction(pointer);
    

    Note that the pointer returned to the callback has to be dereferenced with Pointer_stringify.

    You can find example code like this on GitHub.

提交回复
热议问题