我在 iOS 应用程序中使用 JavaScriptCore 库,我正在尝试实现 setTimeout 函数。
setTimeout(func, period)
启动应用程序后,将创建具有全局上下文的 JSC 引擎,并将两个函数添加到该上下文中:
_JSContext = JSGlobalContextCreate(NULL);
[self mapName:"iosSetTimeout" toFunction:_setTimeout];
[self mapName:"iosLog" toFunction:_log];
这是将具有所需名称的全局 JS 函数映射到静态目标 C 函数的本机实现:
- (void) mapName:(const char*)name toFunction:(JSObjectCallAsFunctionCallback)func
{
JSStringRef nameRef = JSStringCreateWithUTF8CString(name);
JSObjectRef funcRef = JSObjectMakeFunctionWithCallback(_JSContext, nameRef, func);
JSObjectSetProperty(_JSContext, JSContextGetGlobalObject(_JSContext), nameRef, funcRef, kJSPropertyAttributeNone, NULL);
JSStringRelease(nameRef);
}
这是目标C setTimeout 函数的实现:
JSValueRef _setTimeout(JSContextRef ctx,
JSObjectRef function,
JSObjectRef thisObject,
size_t argumentCount,
const JSValueRef arguments[],
JSValueRef* exception)
{
if(argumentCount == 2)
{
JSEngine *jsEngine = [JSEngine shared];
jsEngine.timeoutCtx = ctx;
jsEngine.timeoutFunc = (JSObjectRef)arguments[0];
[jsEngine performSelector:@selector(onTimeout) withObject:nil afterDelay:5];
}
return JSValueMakeNull(ctx);
}
延迟一段时间后应该在 jsEngine 上调用的函数:
- (void) onTimeout
{
JSValueRef excp = NULL;
JSObjectCallAsFunction(timeoutCtx, timeoutFunc, NULL, 0, 0, &excp);
if (excp) {
JSStringRef exceptionArg = JSValueToStringCopy([self JSContext], excp, NULL);
NSString* exceptionRes = (__bridge_transfer NSString*)JSStringCopyCFString(kCFAllocatorDefault, exceptionArg);
JSStringRelease(exceptionArg);
NSLog(@"[JSC] JavaScript exception: %@", exceptionRes);
}
}
用于 javascript 评估的本机函数:
- (NSString *)evaluate:(NSString *)script
{
if (!script) {
NSLog(@"[JSC] JS String is empty!");
return nil;
}
JSStringRef scriptJS = JSStringCreateWithUTF8CString([script UTF8String]);
JSValueRef exception = NULL;
JSValueRef result = JSEvaluateScript([self JSContext], scriptJS, NULL, NULL, 0, &exception);
NSString *res = nil;
if (!result) {
if (exception) {
JSStringRef exceptionArg = JSValueToStringCopy([self JSContext], exception, NULL);
NSString* exceptionRes = (__bridge_transfer NSString*)JSStringCopyCFString(kCFAllocatorDefault, exceptionArg);
JSStringRelease(exceptionArg);
NSLog(@"[JSC] JavaScript exception: %@", exceptionRes);
}
NSLog(@"[JSC] No result returned");
} else {
JSStringRef jstrArg = JSValueToStringCopy([self JSContext], result, NULL);
res = (__bridge_transfer NSString*)JSStringCopyCFString(kCFAllocatorDefault, jstrArg);
JSStringRelease(jstrArg);
}
JSStringRelease(scriptJS);
return res;
}
在整个设置之后,JSC 引擎应该评估这个:
[jsEngine evaluate:@"iosSetTimeout(function(){iosLog('timeout done')}, 5000)"];
JS执行调用native _setTimeout
,五秒后调用native, onTimeout
crash发生在JSObjectCallAsFunction
. timeoutCtx
变为无效。听起来超时函数上下文是本地的,并且在此期间垃圾收集器会在 JSC 端删除该上下文。
有趣的是,如果_setTimeout
为了JSObjectCllAsFunction
立即调用而更改函数,而不等待超时,那么它会按预期工作。
如何防止在这种异步回调中自动删除上下文?