Subj : Re: Help with rooting, JSStrings and JS_DefineFunction To : netscape.public.mozilla.jseng From : altan Date : Thu Dec 02 2004 09:52 am Brendan, Thank you. That was very helpful. .... Altan Brendan Eich wrote: > Altan wrote: > > When interfacing a C function with JavaScript, JS_DefineFunction is > > used. Let's assume the following C function is eventually called > > > > constructInternal( > > JSContext *cx, > > JSObject **obj, > > uintN argc, > > jsval *argv, > > jsval *rval) > > { > > ... > > } > > > > If one (or more) of the parameters passed in the argv is a JSString > > and the C code will continue to reference this JSString after > > constructInternal returns, do I need to worry about this string being > > garbage collected? For example, might it be garbage collected if the > > script containing the string that caused constructInternal to be > > executed terminates or under any other conditions? > > > > Sure; consider a caller who says "constructInternal('foo ' + bar)' where > bar's value is converted to a string if it's not one already, > concatenated with 'foo ', and passed so that constructInternal receives > the concatenation in argv[0]. That string is temporary, it need not > live any longer than the call, since there are no other references to it. > > > > In general, what are the rules for keeping pointers to arbitrary > > argv's after a C function returns? Must I use JS_AddRoot in all such > > cases? > > > That's a sure and safe way (don't forget to JS_RemoveRoot; try to use > JS_AddNamedRoot for GC_MARK_DEBUG's sake). There are other ways, such > as "locking" the GC-thing (JS_LockGCThing), arranging for a root scanned > by a JSClass.mark hook to protect the string, where the object with that > JSClass lives as long as you need the string to live, and similar > techniques. > > It helps to think about references forming a directed graph that the GC > scans, and pondering "what else keeps this string or object from being > garbage?" > > /be > > > > Thanks in advance for any help. > > > > ... Altan .