문제

I'm embedding SpiderMonkey and am attempting to use JS_BindCallable. However, I have a JSObject * that I want to use as the newThis, yet the function takes a JSRawObject. The documentation on JSRawObject seems sparse and the header files haven't provided any clues.

It appears to compile if I simply pass it a JSObject *, without crashing, but I'm not sure why, and that makes me uncomfortable. Further, it doesn't seem to work - not sure if that's because of this issue or because of something else. In particular, I'm doing this:

JSObject *result = JS_NewObject(cx, NULL, NULL, NULL);

//create .finish() callable
int props = JSPROP_READONLY | JSPROP_PERMANENT | JSPROP_ENUMERATE;
JS_DefineFunction(cx, result, "finish", my_native_func, 0, props);

//bind finish to always use 'this'
jsval jsvFinishFuncObj;
JS_GetProperty(cx, result, "finish", &jsvFinishFuncObj);
JSObject *finishFuncObj = JSVAL_TO_OBJECT(jsvFinishFuncObj);
JS_BindCallable(cx, finishFuncObj, result);
도움이 되었습니까?

해결책

JSRawObject was a typedef for JSObject*, so your usage is right. We did this, because in future version all APIs are going to take handles, so like JS::HandleObject. You might read about that upcoming change here: https://developer.mozilla.org/en-US/docs/SpiderMonkey/31#Migrating_to_SpiderMonkey_31

I think you have to use the return value of JS_BindCallable and overwrite "finish" with it. Actually you might do something like this:

//define a function on an object which is bound to the object it is defined on
JSBool JS_DefineBoundFunction(JSContext *cx, JSObject *obj, const char *name,
                              JSNative call, unsigned int nargs, unsigned int attrs) {
    JSFunction *func = JS_NewFunction(cx, call, nargs, 0, NULL, name);
    if (!func) {
        return JS_FALSE;
    }
    JSObject *funcObj = JS_GetFunctionObject(func);
    if (!funcObj) {
        return JS_FALSE;
    }
    JSObject *boundFuncObj = JS_BindCallable(cx, funcObj, obj);
    if (!boundFuncObj) {
        return JS_FALSE;
    }
    return JS_DefineProperty(cx, obj, name,
                             OBJECT_TO_JSVAL(boundFuncObj),
                             NULL, NULL, attrs);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top