Calling C++ function from JavaScript through Webassembly
-
I need to call a function in my Qt program (C++) from JavaScript but I don't know how Qt calls C++ functions from JS.
Using this does not work since Qt does not export ccall.
var result = Module.ccall( 'myFunction', // name of C function null, // return type null, // argument types null // arguments );
How can I do this?
-
You need to export those by adding linker arguments:
-
@lorn-potter said in Calling C++ function from JavaScript through Webassembly:
Could you provide an example of how exactly should this be used in Qt? I am trying to export a simple function returning an integer and even that fails. I've added -s EXPORTED_FUNCTIONS=_getInt and -sEXPORTED_RUNTIME_METHODS=ccall,cwrap as an argument and even tried adding QT_WASM_EXPORTED_FUNCTIONS =_getInt to my .pro file. Both failed.
Here's my function:
extern "C" {
int getInt() {
int number = 5;
return number;
}
}I tried writing a minimal example using C++-only code and everything worked properly. Yet, in Qt, I keep receiving undefined symbol errors for the getInt() function, ccall, cwrap. What I am a bit curious about, is that the "Module" variable is not accessible in the browser. Thus there's no possibility to interact with the WASM module directly. After digging into the qtloader.js I found out it might be accessible through qtLoader.module(). However, calling qtLoader.module().ccall returns Uncaught RuntimeError: Aborted('ccall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ))
I am using Qt 6.4.0 with emscripten 3.1.4 on macOS 12.6 with XCode 14.1
-
If anyone will have this problem in the future, the EMSCRIPTEN_KEEPALVIE macro seems to seal the deal:
extern "C" {
int EMSCRIPTEN_KEEPALIVE getInt() {
int number = 5;
return number;
}
}The previously mentioned compilation arguments are not required when using this macro.
The function has to be called in a following manner: qtLoader.module()._getInt() -
I figured out how to export custom functions, but there's still a problem with exporting the runtime ones. I am adding the -s EXPORTED_RUNTIME_METHODS=UTF8ToString argument and keep receiving "Uncaught RuntimeError: Aborted('UTF8ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ))" error.