2

我正在为 Cocos2D-JavaScript 做一些额外的绑定,并且必须了解它是如何工作的。SpiderMonkey 的JS_WrapObject()定义是jsapi.h做什么的?我似乎找不到好的文档,它也没有出现在JSAPI Reference中。它的用法如下,例如:

JSObject* JSB_NewGlobalObject(JSContext* cx, bool empty)
{
    JSObject* glob = JS_NewGlobalObject(cx, &global_class, NULL);
    ...
    JS_WrapObject(cx, &glob);
    return glob;
}
4

1 回答 1

2

This question is a quite old one, but maybe the answer will help somebody.

This function makes a cross-compartment wrapper for the given JS object. Given that JS object created for one compartment cannot be shared with the different one directly, there is a concept of a wrapper that has to be prepared in order to share the same instance of a JS object between different compartments.

A compartment can be treated as a container that has its own GC and shares a number of related objects. For instance every global object in the SpiderMonkey has its own compartment.

Let's say you have two independent global objects in the JS context. You can evaluate one script in the context of the first global object, then you can use the result value as an argument to the second script that will be evaluated using the second global object. But in order to do so, you have to wrap it using a cross-compartment wrapper.

One important thing here is the fact that JS_WrapObject prepares a wrapper for the active compartment, so it may be necessary to make the expected compartment the active one using JSAutoCompartment class for example.

于 2014-12-06T23:27:19.970 回答