Passing JS function to Emscripten-generated code

Lóránt Pintér picture Lóránt Pintér · Sep 10, 2012 · Viewed 7.6k times · Source

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:

JavaScript:

function callback(message) {
    alert(message);
}

ccall("my_c_function", ..., callback);

C++:

void my_c_function(whatever_type_t *callback) {
    callback("Hello World!");
}

Is this possible somehow?

Answer

Daniel Baulig picture Daniel Baulig · Nov 7, 2013

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)