2017-09-20 115 views
6

我正在尝试一个简单的示例来调用C编译为JavaScript的.wasm函数。“声明失败:您需要等待运行时准备就绪”在JavaScript中调用C函数时出错

这是counter.c文件:

#include <emscripten.h> 

int counter = 100; 

EMSCRIPTEN_KEEPALIVE 
int count() { 
    counter += 1; 
    return counter; 
} 

我把它用emcc counter.c -s WASM=1 -o counter.js编译。

main.js JavaScript文件:

const count = Module.cwrap('count ', 'number'); 
console.log(count()); 

index.html文件只加载无论在身体,没有别的.js文件:

<script type="text/javascript" src="counter.js"></script> 
<script type="text/javascript" src="main.js"></script> 

我得到的错误是:

Uncaught abort("Assertion failed: you need to wait for the runtime to be ready (e.g. wait for main() to be called)") at Error

当我tr y致电count(),电话号码main.js如何等待运行时准备就绪?

回答

5

我找到了一个快速解决方案。我需要修改main.js到:

Module['onRuntimeInitialized'] = onRuntimeInitialized; 
const count = Module.cwrap('count ', 'number'); 

function onRuntimeInitialized() { 
    console.log(count()); 
} 

这改变了在由emscripten产生的counter.js脚本中定义的Module对象。

0

对方回答的作品,按照规定根据“我怎么知道当页面完全加载,它是安全地调用编译的功能呢?”头,这里的文章还提到了另一种方式来等待调用here代码,你包括你的C主函数/ C++代码,通过C/C++为Javascript API,像这样调用javascript函数:

#include <emscripten.h> 
int main() { 
    ES_ASM(const count = Module.cwrap('count ', 'number'); console.log(count());); 
    return 0; 
} 

这工作,因为当运行时初始化的主要功能始终执行。

相关问题