简体   繁体   English

是否有与SpiderMonkey中的PyCapsule等效/相似的东西?

[英]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, ie it's perfect to pass around stuff that is used only by the C code. 嵌入Python时,可以使用PyCapsule类型创建一个包含C指针的对象,该对象无法从Python代码中进行修改,即,完美地传递仅由C代码使用的内容。

Since my application also supports JavaScript via the SpiderMonkey engine I'm looking for something similar in SpiderMonkey. 由于我的应用程序还通过SpiderMonkey引擎支持JavaScript,因此我想在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. 我知道我可以创建自定义JSClassJSCLASS_HAS_PRIVATE国旗,但我不知道是否有另一种更简单/更轻量级的方法。

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. 它定义了一个新类“ Resource”来存储指针。 While not as pretty as the python way it's still very straightforward: 虽然不像python那样漂亮,但它仍然非常简单:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM