首页 > 解决方案 > 断言失败:在 .js 文件 (emscripten) 中调用 c 函数时,在运行时初始化错误之前调用了本机函数 `int_sqrt`

问题描述

我无法在另一个 JavaScript 文件中调用 C 函数,它给出了错误“在运行时初始化之前调用” 请参阅此链接

我按照给定链接中的描述在 emscripten 中编译了 C 代码,并在我的 test.js 文件中使用了生成的 asm.js 文件。用于生成 asm 的命令:-

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

test.js 文件中的代码:

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

当我运行时node test它给出了错误

abort(Assertion failed: native function `int_sqrt` called before runtime initialization)

标签: emscriptenasm.js

解决方案


你应该等待运行时初始化。
尝试这个:

var Module = require("./lib.js");
var result = Module.onRuntimeInitialized = () => {
    Module.ccall('myFunction', // name of C function 
        null, // return type
        null, // argument types
        null // arguments
   );
}

推荐阅读