C++ 调用 JS 函数 JsFunc(),将 C 函数 MyCFunc() 作为参数传递。JsFunc() 调用 MyCFunc() 并将 JS 回调函数作为参数传递。
如何在 MyCFunc() 中保存 JS 回调函数参数,以便以后可以从 C++ 的其他地方调用它?
主文件
#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;
}
测试.js
function JsFunc(cfunc) {
print("Entering testCFunc" );
cfunc(function () {
print("In lambda function()");
});
print("Exiting testCFunc");
}