[quickjs-devel] Re: Is there any mechanism to 'hook' gabage collection?
- From: ShaJunxing <shajunxing@xxxxxxx>
- To: quickjs-devel@xxxxxxxxxxxxx, Alex Protasenko <alex@xxxxxxxxxxxxxx>
- Date: Sat, 20 Mar 2021 13:50:01 +0800
在 2021/3/19 下午11:41, Alex Protasenko 写道:
If you've implemented a custom JS class in C, use the finalizer method
to cleanup any state when its instance is being collected.
E.g.
static JSClassDef js_myclass_class = {
"MyClass",
.finalizer = js_myclass_finalizer,
};
On 3/19/21 2:05 AM, ShaJunxing wrote:
My project uses a lot of C malloc operations. Now I have to write
additional functions or class member functions to manually free them.
I wonder if there is something like class destructor or object gc
notifications or something else so that my allocated memory can be
automatic freed with those objects? Any suggestion? Thanks. 😁
Thank you, I wrote my class "ClassWithDestructor" and expect if exists a
method named "destructor", it will be called on finalization. My code is:
static void js_dtor_class_finalizer(JSRuntime *rt, JSValue obj) {
JSObject *p = JS_VALUE_GET_OBJ(obj);
JSContext *ctx = p->u.cfunc.realm;
if (ctx) {
JSValue dtor = JS_GetPropertyStr(ctx, obj, "destructor");
if (JS_IsFunction(ctx, dtor)) {
JSValue result = JS_Call(ctx, dtor, obj, 0, NULL);
if (JS_IsException(result)) { // js_std_dump_error in
quickjs-libc.c
js_std_dump_error(ctx);
}
}
}
}
static JSClassDef js_dtor_class = {
"ClassWithDestructor",
.finalizer = js_dtor_class_finalizer,
};
But compiler says "error: dereferencing pointer to incomplete type
‘JSObject {aka struct JSObject}’ JSContext *ctx = p->u.cfunc.realm;"
Typedef of JSObject is in quickjs.c, not in quicjs.h, JS_Call needs
JSContext, I cannot get it. sad.😭
Other related posts: