[Ovmsdev] Duktape Persistent Function References
Mark Webb-Johnson
mark at webb-johnson.net
Wed Jul 15 14:12:58 HKT 2020
@Michael this is probably for you.
I am trying to implement javascript command registration. The idea is that a javascript module can call something like:
OvmsCommand.Register(basecommand, name, title, callbackfn, usage, min, max)
Then we reflect that into MyCommandApp.RegisterCommand, and keep a track of which command is for which javascript callbackfn. When the command is executed, we pass it into duktape.
I also have tracking for javascript module loading and unloading, so I can DeregisterCommand() if duktape is reloaded (and also protected against commands being registered in short-lived scripts run from the command line).
To implement this, I need to store the callbackfn as a persistent reference to a duktape javascript function.
The issue with callback function references in duktape is summarised here:
https://wiki.duktape.org/howtonativepersistentreferences <https://wiki.duktape.org/howtonativepersistentreferences>
When a Duktape/C function is called, Duktape places the call arguments on the value stack. While the arguments are on the value stack, they're guaranteed to be reachable and the Duktape/C function can safely work with the arguments.
However, when the Duktape/C function returns, the value stack is unwound and references in the function's value stack frame are lost. If the last reference to a particular value was in the function's value stack frame, the value will be garbage collected when the function return is processed.
The standard approach is to store the reference back in the duktape duk_push_global_stash so it won’t get garbage-collected. But, that seems messy.
I see that Michael has already implemented something that seems similar in ovms_script.{h, cpp}, for the async http callbacks. Presumably to avoid this issue. But, the approach seems very different, and I am not sure if it is stopping _all_ garbage collection for the duration of the async query, or just that particular object being garbage collected. The work seems extensive (quite a few objects involved).
So @Michael, any suggestions for this? I don’t want to reinvent the wheel...
Regards, Mark.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.openvehicles.com/pipermail/ovmsdev/attachments/20200715/f89bbeb6/attachment.html>
More information about the OvmsDev
mailing list