Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call C++ function pointer from Javascript

Is it possible to pass function pointers from C++ (compiled into Javascript using Emscripten) to directly-written JS? I've found ways of creating function pointers of Javascript functions to pass to C++, but not a way of exposing a function pointer, given a value at runtime in C++ code, to Javascript.

Code-wide, what I'm after is to be able to complete the code snippet below in order to call the function passed as cFunctionPointer where I'm doing the console.log

void passToJs(void (*cFunctionPointer)()) {
  EM_ASM_ARGS({
    // Prints out an integer. Would like to be able to
    // call the function it represents.
    console.log($0);
  }, cFunctionPointer);
}
like image 277
Michal Charemza Avatar asked Mar 21 '26 06:03

Michal Charemza


1 Answers

Found the answer at https://stackoverflow.com/a/25584986/1319998. You can use the Runtime.dynCall function:

void passToJs(void (*cFunctionPointer)()) {
  EM_ASM_ARGS({
    Module.Runtime.dynCall('v', $0, []);
  }, cFunctionPointer);
}

The 'v' is the signature of a void function that doesn't take any arguments.

Apparently it supports other signatures, such as 'vii', which is a void function that takes 2 integer arguments. The integer arguments would then have to passed in the array which is the 3rd argument of Runtime.dynCall.

like image 96
Michal Charemza Avatar answered Mar 23 '26 19:03

Michal Charemza