5

I am not able to call a C function in another JavaScript file, it is giving the error 'called before runtime initialization' please refer to this link

I compiled the C code in emscripten as described in the given link and used generated asm.js file in my test.js file. command used to generate asm :-

emcc test/hello.cpp -o hello.html -s EXPORTED_FUNCTIONS="['_int_sqrt']" -s EXPORTED_RUNTIME_METHODS="["ccall", "cwrap"]"

code in test.js file :

var Module = require('./asm.js');
var test =  Module.cwrap('int_sqrt', 'number', ['number']);
console.log(test(25));

and when I run node test it gives the error

abort(Assertion failed: native function `int_sqrt` called before runtime initialization)
David Buck
  • 3,752
  • 35
  • 31
  • 35
mysterious
  • 51
  • 1
  • 4

2 Answers2

7

you should wait for runtime init.
try this:

var Module = require("./lib.js");
var result = Module.onRuntimeInitialized = () => {
    Module.ccall('myFunction', // name of C function 
        null, // return type
        null, // argument types
        null // arguments
   );
}
  • 3
    eventually, I got the answer and I guess if we add WASM = 0 flag while compiling then we might not wait for runtime init. And thankyou so much for your answer sir. – mysterious Sep 07 '20 at 04:35
1

I had the same issue while using emscripten and this has worked for me:

<script>
    Module.onRuntimeInitialized = () => { Module.functionName(param); }
</script>

Where functionName is the name of the function that you want to invoke and param is the value that you want to pass to it.

Raydelto Hernandez
  • 2,200
  • 2
  • 16
  • 11