Call C++ function pointer from Javascript

拟墨画扇 提交于 2019-12-10 21:39:34

问题


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);
}

回答1:


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.



来源:https://stackoverflow.com/questions/29319208/call-c-function-pointer-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!