Question

I'm working on doing some extra bindings for Cocos2D-JavaScript and am having to learn how it all works. What does SpiderMonkey's JS_WrapObject() defined in jsapi.h do? I can't seem to find good docs on it and it doesn't appear in the JSAPI Reference. It's used as follows, for example:

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

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top