Subj : Re: how to make C functions return array to js? To : Oyku Gencay From : Brendan Eich Date : Wed Mar 17 2004 10:02 am Oyku Gencay wrote: > Hi folks, > > How can I return an array to javascript from a C function? I have a > native C function which returns an array. When I run this I get a > segfault. Where? What stack? > The function code is; > > static JSBool > TestingArraysAsReturn(JSContext *cx, JSObject *obj, uintN argc, > jsval *argv, jsval *rval) { > > JSObject *js_array ; > js_array = JS_NewArrayObject(cx,0,NULL); > for (i = 1 ; i <= 5 ; ++i) { > jsval *js; > js = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, "testing")); Bug: you are assigning a jsval to a jsval* here, surely your compiler warned you? You want jsval v = STRING_TO_JSVAL(str); where str is set to the result of JS_NewStringCopyZ, and you test that result against null first, returning false to handle out-of-memory errors. > JS_SetElement(cx,js_array,i,js); So you want &v, not js, here. > } > *rval = OBJECT_TO_JSVAL(js_array); > return JS_TRUE; > } Please also read http://www.mozilla.org/js/spidermonkey/gctips.html, note the need to root as you go. Storing *rval late is not good -- what if the GC ran from one of the JS_NewStringCopyZ calls? /be .