Skip to content

Commit c6d17c7

Browse files
committed
Add finalize callback to userdata objects.
When a userdata object is garbage collected, we should invoke a callback to client code to let it know that the associated userdata pointer is no longer in use.
1 parent 40dd4a2 commit c6d17c7

File tree

4 files changed

+7
-2
lines changed

4 files changed

+7
-2
lines changed

jsgc.c

+2
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@ static void jsG_freeobject(js_State *J, js_Object *obj)
4848
js_regfree(obj->u.r.prog);
4949
if (obj->type == JS_CITERATOR)
5050
jsG_freeiterator(J, obj->u.iter.head);
51+
if (obj->type == JS_CUSERDATA && obj->u.user.finalize)
52+
obj->u.user.finalize(J, obj->u.user.data);
5153
js_free(J, obj);
5254
}
5355

jsvalue.c

+2-1
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ void js_newcconstructor(js_State *J, js_CFunction cfun, js_CFunction ccon, const
432432
}
433433
}
434434

435-
void js_newuserdata(js_State *J, const char *tag, void *data)
435+
void js_newuserdata(js_State *J, const char *tag, void *data, js_Finalize finalize)
436436
{
437437
js_Object *prototype = NULL;
438438
js_Object *obj;
@@ -444,6 +444,7 @@ void js_newuserdata(js_State *J, const char *tag, void *data)
444444
obj = jsV_newobject(J, JS_CUSERDATA, prototype);
445445
obj->u.user.tag = tag;
446446
obj->u.user.data = data;
447+
obj->u.user.finalize = finalize;
447448
js_pushobject(J, obj);
448449
}
449450

jsvalue.h

+1
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ struct js_Object
112112
struct {
113113
const char *tag;
114114
void *data;
115+
js_Finalize finalize;
115116
} user;
116117
} u;
117118
js_Object *gcnext;

mujs.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ typedef struct js_State js_State;
2929
typedef void *(*js_Alloc)(void *memctx, void *ptr, unsigned int size);
3030
typedef void (*js_Panic)(js_State *J);
3131
typedef void (*js_CFunction)(js_State *J);
32+
typedef void (*js_Finalize)(js_State *J, void *p);
3233

3334
/* Basic functions */
3435
js_State *js_newstate(js_Alloc alloc, void *actx);
@@ -125,7 +126,7 @@ void js_newnumber(js_State *J, double v);
125126
void js_newstring(js_State *J, const char *v);
126127
void js_newcfunction(js_State *J, js_CFunction fun, const char *name, unsigned int length);
127128
void js_newcconstructor(js_State *J, js_CFunction fun, js_CFunction con, const char *name, unsigned int length);
128-
void js_newuserdata(js_State *J, const char *tag, void *data);
129+
void js_newuserdata(js_State *J, const char *tag, void *data, js_Finalize finalize);
129130
void js_newregexp(js_State *J, const char *pattern, int flags);
130131

131132
void js_pushiterator(js_State *J, int idx, int own);

0 commit comments

Comments
 (0)