Reputation: 7138
I am trying out a simple example to call a C function compiled to .wasm with JavaScript.
This is the counter.c
file:
#include <emscripten.h>
int counter = 100;
EMSCRIPTEN_KEEPALIVE
int count() {
counter += 1;
return counter;
}
I compiled it using emcc counter.c -s WASM=1 -o counter.js
.
My main.js
JavaScript file:
const count = Module.cwrap('count ', 'number');
console.log(count());
My index.html
file only loads both .js files in the body, nothing else:
<script type="text/javascript" src="counter.js"></script>
<script type="text/javascript" src="main.js"></script>
The error I am getting is:
Uncaught abort("Assertion failed: you need to wait for the runtime to be ready (e.g. wait for main() to be called)") at Error
when I try to call count()
in main.js
. How can I wait for the runtime to be ready?
Upvotes: 13
Views: 4270
Reputation: 304
The other answer works, as specified here under the "How can I tell when the page is fully loaded and it is safe to call compiled functions?" header, where the article also mentions another way to wait to call code where you include a main function in your C/C++ code that calls a javascript function through the C/C++ to Javascript API like so:
#include <emscripten.h>
int main() {
EM_ASM(const count = Module.cwrap('count ', 'number'); console.log(count()););
return 0;
}
This works because the main function always executes when the runtime is initialized.
Upvotes: 2
Reputation: 7138
I found a quick solution. I needed to modify main.js
to:
Module['onRuntimeInitialized'] = onRuntimeInitialized;
const count = Module.cwrap('count ', 'number');
function onRuntimeInitialized() {
console.log(count());
}
This alters the Module
object that is defined in the counter.js
script generated by emscripten.
Upvotes: 12