so I’ve had a look online and can’t really find much. I was hoping someone might have experience setting up a .registerCallback() method in an embedded quickjs project.
the type of use would be like this in the script:
import {Class} from 'Class'
let c = new Class();
c.registerCallback(callbackfunc);
function callbackfunc() {}
the addCallbackMethod in the cpp file:
// Custom method function: Performs a custom operation on the object
static JSValue myClass_addCallbackMethod(
JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
auto* object = static_cast<myClassData *>(
JS_GetOpaque2(ctx, this_val, myClassId));
// If no callback function is provided or the provided argument is not a function, return an exception
if (argc == 0 || !JS_IsFunction(ctx, argv[0]))
return JS_ThrowTypeError(ctx, "Expected a function as argument");
// Store the callback function in the object
object->registeredCallback = JS_DupValue(ctx, argv[0]);
return JS_UNDEFINED;
}
I’ve had a go and I thought I was on the right track but it seems to give me seg faults whenever I try and access the object’s property that’s holding the function in my main.cpp
2
Answers
This code assumes you have a QuickJS context ctx where you want to register the callback function. It defines the callback function myCallback and a wrapper function js_myCallback that calls the callback function. Then, it registers the callback function by assigning it to a property named "myCallback" on the global object.
Remember to include the appropriate QuickJS headers and link against the QuickJS library when compiling your embedded project.
The fifth line calls the js_eval() function to evaluate the JavaScript string my_callback(123);.
The sixth line calls the js_free_context() function to dispose of the context.
The seventh line returns 0 to indicate that the program exited successfully.