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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #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> |