Calling JS from C using EM_ASM in Emscripten

A very simple for calling JS from C and returning a value. Create the following C program, in the file calljs.c, it makes a single call to js_receive which will be our Javascript function:

#include <stdio.h>
#include <emscripten.h>

int main() {
  int ret = EM_ASM_INT({
    return js_receive($0,$1,$2,$3);
  }, 1,"two",3,4);

  printf("returned: %d\n",ret);
}

compile it with: <pre>emcc calljs.c -o calljs.js</pre>

It will then call the JS code which can access the variables and string. Here's an example complete html file:

[sourcecode language="html"]
 <!DOCTYPE html>
<html>
<body>

<script>

function js_receive(a,b,c,d) {

  var bstr = Pointer_stringify(b);
  document.write(a + " " + bstr + " " + c + " " + d);

  return 42;
}

</script>

<script src="calljs.js"></script>

</body>
</html>

Comments are closed.