"Assertion failed: you need to wait for the runtime to be ready" Error when calling a C function in JavaScript

Viewed 3592

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?

2 Answers

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.

Related