Emscripten calling JS from C and returning by reference (pointer)
JS code can manipuate memory directly using setValue, here’s a quick example of returning by reference. The C code is as follows:
#include <stdio.h> #include <emscripten.h> #include <string.h> int main() { char buffer[10]; strcpy(buffer,"nothing"); int ret = EM_ASM_INT({ return js_receive($0,$1,$2,$3); }, 1,buffer,3,4); printf("returned: %d\n",ret); printf("buffer : %s\n",buffer); char call[100]; strcpy(call,"alert('"); strcat(call,buffer); strcat(call,"')"); emscripten_run_script(call); }
And can be called using the following JS which modifies the contents of buffer:
<!DOCTYPE html> <html> <body> <script> function js_receive(a,b,c,d) { var bstr = Pointer_stringify(b); document.write(a + " " + bstr + " " + c + " " + d); setValue(b , 84, 'i8'); setValue(b+1, 87, 'i8'); setValue(b+2, 79, 'i8'); setValue(b+3, 0, 'i8'); return 42; } </script> <script src="calljs.js"></script> </body> </html>