Subj : Re: Is this gc-safe To : netscape.public.mozilla.jseng From : Brendan Eich Date : Wed Aug 31 2005 10:29 am Thomas Sondergaard wrote: > On my javascript object I want a property called 'geometry' that returns > an array with the upper left and lower right corners of a box, ie. the > value of the property might be: [ [0,0], [1,1] ]. > > This is the body of the getter function for the property. I wonder if > this is okay, or do I need to root the objects as I create them to avoid > garbage collection? > > vector ul = getUpperLeftCorner(); > vector lr = getLowerRightCorner(); > jsval ulj[2] = { > DOUBLE_TO_JSVAL(JS_NewDouble(ctx, ul[0])), > DOUBLE_TO_JSVAL(JS_NewDouble(ctx, ul[1])), If your malloc implementation can return null, you should null-test these and propagate failure (meaning out of memory error was reported) if either returns null. You should also use JS_NewNumberValue, for two reasons: - It optimizes integral jsdoubles that fit in a jsval, normalizing them so they compare with other such normalized doubles. - JS_NewNumberValue returns the tagged jsval for you via an out param, and returns false on failure (error thrown as exception, or reported if out of memory). > }; > jsval lrj[2] = { > DOUBLE_TO_JSVAL(JS_NewDouble(ctx, lr[0])), > DOUBLE_TO_JSVAL(JS_NewDouble(ctx, lr[1])), > }; > jsval ret[2] = { > OBJECT_TO_JSVAL(JS_NewArrayObject(ctx, 2, ulj)), > OBJECT_TO_JSVAL(JS_NewArrayObject(ctx, 2, lrj)) > }; > *vp = OBJECT_TO_JSVAL(JS_NewArrayObject(ctx, 2, ret)); > return JS_TRUE; > > > What jsapi function calls can invoke the gc? The GC's allocator can invoke the collector, so you need to root as you go. Since you are using C++, you might find JSAutoLocalRootScope in the latest CVS jsapi.h handy. /be .