C++ calls the JS function, JsFunc(), passsing a C-function, MyCFunc(), as a parameter. JsFunc() calls MyCFunc() passsing a JS callback function as parameter.
How do I save in MyCFunc() the JS callback function parameter so that I can call it later from somewhere else in C++?
main.cpp
#include <duktape/src/duktape.h>
#include <cassert>
duk_ret_t MyCFunc(duk_context* ctx) {
assert(duk_is_function(ctx, -1) );
(void) duk_require_function(ctx, -1);
// 1.- How to save the callback function parameter
// so that it can be used later on, say in main()?
return 0; // nothing returned
}
int main() {
duk_context* ctx = duk_create_heap_default();
assert(ctx != nullptr);
if (duk_peval_file(ctx, "../../src/jscallback_forum/test.js") != 0) {
printf("Error: %s\n", duk_safe_to_string(ctx, -1));
exit(1);
}
duk_pop(ctx); /* ignore result */
duk_push_global_object(ctx);
duk_bool_t isSuccess = duk_get_prop_string(ctx, -1 , "JsFunc");
assert(isSuccess != false);
// pass MyCFunc as parameter to JsFunc
duk_push_c_function(ctx, &MyCFunc, 1); // MyCFunc expects Js callback
if (duk_pcall(ctx, 1) != 0) { // JsFunc call failed
printf("Error: %s\n", duk_safe_to_string(ctx, -1));
}
duk_pop(ctx); /* pop duk_pcall result/error */
duk_pop(ctx); /* pop duk_push_global_object */
// 2. How do I retrieve the JS callback function
// saved in MyCFunc() and run it?
duk_destroy_heap(ctx);
return 0;
}
test.js
function JsFunc(cfunc) {
print("Entering testCFunc" );
cfunc(function () {
print("In lambda function()");
});
print("Exiting testCFunc");
}