Search code examples
javascriptcspidermonkey

Is there something equivalent/similar to PyCapsule in SpiderMonkey?


When embedding Python there is the PyCapsule type to create an object containing a C pointer which cannot be modified from Python code, i.e. it's perfect to pass around stuff that is used only by the C code.

Since my application also supports JavaScript via the SpiderMonkey engine I'm looking for something similar in SpiderMonkey. I know that I can create a custom JSClass with the JSCLASS_HAS_PRIVATE flag but I wonder if there's another simpler/more lightweight approach.


Solution

  • There is nothing similar so it is indeed necessary to create a custom class. This is the code I ended up using; it defines a new class "Resource" to store the pointer. While not as pretty as the python way it's still very straightforward:

    // Define the class and give it some private space for the pointer
    static JSClass resource_class = { "Resource", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub,
        JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub,
        JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS };
    
    // Create an object and store the pointer
    JSObject *obj = JS_NewObject(cx, &resource_class, NULL, NULL);
    JS_SetPrivate(cx, obj, MY_POINTER);
    
    // Get the pointer
    void *ptr = JS_GetPrivate(cx, obj);