Subj : (SpiderMonkey Question) Help calling script functions from C To : netscape.public.mozilla.jseng From : zaphodthefirst@hotmail.com (zaphod) Date : Thu Oct 02 2003 04:54 pm Hi, I want to call several functions from a script and allow the script to store global variables inbetween function calls. I have set up a small example where the C code calls the JS 'setvalue' to store a string in a script global variable, and then the C code tries to get the string back though the JS 'getvalue' function. I am not sure I am doing this right: I'm creating a context, a global object, compiling the script, and expecting the script's functions to be part of the global object. When I try this, I get a property count of zero for the global object, an error report that says "TypeError: undefined is not a function", and the first attempted function call fails. 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" ; 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; } void MyReporter(JSContext * context, const char * msg, JSErrorReport * report) { printf("MyReporter: error \"%s\" in file \"%s\", text \"%s\", token \"%s\" !", msg, report->filename, report->linebuf, report->tokenptr); } void MyMain() { JSRuntime * runtime; JSContext * context; JSObject * global; runtime = JS_NewRuntime(8388608); context = JS_NewContext(runtime, 8192); JS_SetErrorReporter(context, MyReporter); MyFillClass(&globalclass, "MyGlobalClass"); global = JS_NewObject(context, &globalclass, NULL, NULL); JS_InitStandardClasses(context, global); JS_CompileScript(context, global, script, (uintN)strlen(script), "static", 0); { 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))); if (!JS_CallFunctionName(context, object, "setvalue", 1, argv, &retv)) { printf("failed on first call"); return; } if (!JS_CallFunctionName(context, object, "getvalue", 0, argv, &retv)) { printf("failed on second call"); return; } printf("Round Trip With (%s)", JS_GetStringBytes(JSVAL_TO_STRING(retv))); } JS_DestroyRuntime(runtime); } I would greatly appreciate any help, thanks. .