Subj : Re: (SpiderMonkey Question) Help calling script functions from C To : zaphod From : Brendan Eich Date : Thu Oct 02 2003 08:40 pm zaphod wrote: > > Here is the code (this snippet has been pruned down, > in the real code I check all of the return values from > the JS_* functions and am sure that the runtime, > context and global object are created properly. > > char * script = > " var save; \n" > " \n" > " function setvalue(val) { \n" > " save = val; \n" > " } \n" > " \n" > " function getvalue() { \n" > " return save; \n" > " } \n" > ; Aside: better form is const char script[] = "..." -- you don't want a non-const pointer to non-const chars, you want a (constant by definition) array named script of const chars. > > JSClass globalclass; > > void MyFillClass(JSClass * jsclass, char * name) > { > memset(jsclass, 0, sizeof(*jsclass)); > jsclass->name = name; > jsclass->addProperty = JS_PropertyStub; > jsclass->delProperty = JS_PropertyStub; > jsclass->getProperty = JS_PropertyStub; > jsclass->setProperty = JS_PropertyStub; > jsclass->enumerate = JS_EnumerateStub; > jsclass->resolve = JS_ResolveStub; > jsclass->convert = JS_ConvertStub; > jsclass->finalize = JS_FinalizeStub; > } Trim this further by static initialization of globalclass. No need for MyFillClass. > JS_InitStandardClasses(context, global); > JS_CompileScript(context, global, script, (uintN)strlen(script), "static", 0); Here is your problem. Just compiling script has no effect on global (passing global when pre-compiling, however, does help the compiler to optimize for the case when you then execute script using global as its scope chain). You must execute after compiling. Use JS_EvaluateScript to compile and execute. > > { > char * str; > > jsval argv[2]; > jsval retv; > > JSIdArray * arr = JS_Enumerate(context, object); > printf("global object has %d properties", arr->length); > > str = (char *)JS_malloc(context, strlen("Hello World !") + 1); > strcpy(str, "Hello World !"); > > argv[0] = STRING_TO_JSVAL(JS_NewString(context, str, strlen(str))); Use JS_NewStringCopyZ to combine the JS_malloc and JS_NewString calls and error checking logic. /be .