WebAssembly calling JavaScript methods from wasm i.e. within C++ code

放肆的年华 提交于 2019-12-05 18:13:10

I'm not exactly sure of your use case, but you are missing important steps to be able to use your function testExternalJSMethod. You have two options here:

Option 1 - Library

1 - Define your function in c/c++ .

extern void testExternalJSMethod();

2 - Create a file called myLibrary.js

3 - The JS function needs to be added to the LibraryManager in your library file with the following code:

function makeAlert(text) {
    alert(text);
}

if (typeof mergeInto !== 'undefined') mergeInto(LibraryManager.library, {
    testExternalJSMethod: function() {
        makeAlert("Hello world");
    }
});

4 - If testExternalJSMethod depends on anything outside of its own scope (for example, makeAlert above), make sure to include the script in your html page

<script async type="text/javascript" src="myLibrary.js"></script>

5 - Add option --js-library to your emcc command, and immediately after the relative path to myLibrary.js

emcc ... --js-library myLibrary.js

Option 2 - Passing Pointers

1 - Define your javascript function type in c/c++

typedef void testExternalJSMethod()

2 - Wherever you want this function to be used, accept an int param which will be the function pointer, and cast the pointer to your function

void passFnPointer(int ptr) {
    ((testExternalJSMethod*)ptr)();
}

3 - Use emscripten's addFunction() and store its returned value (the pointer in c/c++)

var fnPtr = Module.addFunction(function () {
    alert("You called testExternalJSMethod");
});

4 - Use the stored pointer value from step 3 to pass to our function passFnPointer

var passFnPointer = Module.cwrap('passFnPointer', 'undefined', ['number']);
passFnPointer(fnPtr);

5 - Add option -s RESERVED_FUNCTION_POINTERS to your emcc command

emcc ... -s RESERVED_FUNCTION_POINTERS=10

Have you tried looking at the Emscripten documentation? It has a whole section on interacting with code that details how to expose C / C++ functions to JavaScript and call JavaScript functions from C / C++.

Emscripten provides two main approaches for calling JavaScript from C/C++: running the script using emscripten_run_script() or writing “inline JavaScript”.

It is worth noting that the Mozilla documentation details plain WebAssembly, whereas Emscripten adds a lot more framework and tooling around WebAssembly in order to make it easier to port large C / C++ codebases.

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