Passing JS function to Emscripten-generated code

前端 未结 5 1528
自闭症患者
自闭症患者 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:54

    A thing that is frequently done in Emscripten is to map strong types to simple ones.

    JS:

    function callback(message) {
        alert(message);
    }
    
    var func_map = {
        0: callback
    };
    
    // C/C++ functions get a _ prefix added
    function _invoke_callback(callback_id, text_ptr) {
        func_map[callback_id](Pointer_stringify(text_ptr));
    }
    
    ccall("my_c_function", ..., 0);
    

    C++:

    // In C/C++ you only need to declare the func signature and
    // make sure C is used to prevent name mangling
    extern "C" void invoke_callback(int callback_id, const char* text);
    
    void my_c_function(int callback_id) {
        invoke_callback( callback_id, "Hello World!" );
    }
    

    And of course, you can add some glue code, so this gets very seamless.

提交回复
热议问题