Far*_*ala 7 javascript c asynchronous promise emscripten
我正在使用 emscripten 编译一个 C 程序,该程序使用我编写的 JavaScript 库,并将它们与--js-library标志链接在一起。我的 C 代码调用库中的一个函数,其中有一个函数Promise,在回调中我希望它将给定的结果写入一些内存,该内存已从 C 调用者传递到 JS 函数中。这是一个例子(catch为了简洁,我省略了 Promise的错误捕获部分):
库.js
mergeInto(LibraryManager.library, {
compute_js: function(input, out_buf) {
do_promise_computation(
input
).then(function(result){
Module.print("Promise Returned fully");
for (var i = 0; i < 8; i++) {
var num = result[i]
{{{makeSetValue('out_buf+(i*4)', 0, 'num', 'i32')}}}
}
});
}
Run Code Online (Sandbox Code Playgroud)
程序.c
#include <stdio.h>
#include <stdint.h>
#include <emscripten.h>
extern void compute_js(int32_t, int64_t*);
int main() {
int32_t input = 1234;
int64_t out_buf[4];
int64_t* out_ptr = (int64_t*)(&out_buf);
printf("Calling Javascript\n");
compute_js(input, out_ptr);
printf("%lld\n", out_buf[0]);
printf("%lld\n", out_buf[1]);
}
Run Code Online (Sandbox Code Playgroud)
在没有为库编写的 Promise 的其他函数中,我已经能够成功地将数据写入 C 代码给出的缓冲区,但是这一次,输出返回如下:
Calling Javascript
0
0
Promise Returned fully
Run Code Online (Sandbox Code Playgroud)
但是我希望能够等待 Promise 的结果,然后将其写入 C 代码,以便在 JavaScript 调用之后的 C 代码中Promise Returned Fully的printf语句之前。有没有办法用 emscripten 做到这一点?
使用ASYNCIFY_FUNCTIONS和_emscripten_async_resume.
https://kripken.github.io/emscripten-site/docs/porting/asyncify.html