I am using emscripten to compile a C program which makes use of a JavaScript library I have written, and I'm linking them together with the --js-library
flag. My C code calls a function in the library which has a Promise
in it, and in the callback I want it to write the given result to some memory which has been passed into the JS function from the C caller. Here is an example (I omitted the error-catching catch
part of the Promise for brevity):
lib.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')}}}
}
});
}
program.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]);
}
In other functions, without Promises, that I've written for the library, I have been able to successfully write the data to the buffer given from the C code, but this time, the output comes back as follows:
Calling Javascript
0
0
Promise Returned fully
But I want to be able to wait for the result from the Promise and then write it into the C code, so that Promise Returned Fully
comes before the printf
statements in the C code which are after the JavaScript call. Is there a way to do this with emscripten?
Use ASYNCIFY_FUNCTIONS
and _emscripten_async_resume
.
https://kripken.github.io/emscripten-site/docs/porting/asyncify.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With