iMonkey在 iOS 应用程序中嵌入 JS 运行时看起来是一种有趣的方式,但我找不到任何关于如何实际运行一些 JS 代码的示例。
我可以构建/链接库,包括 jsapi.h header (来自 src 目录),但是当我尝试来自 spider 的一些示例代码时,它会遇到各种链接器错误(“未定义的体系结构符号...”)猴子(见下文)。需要明确的是,这几乎是从另一个站点上与 Mac 相关的帖子中复制粘贴的,我完全不确定是否应该这样做。我确定我的架构(模拟器)有正确的静态库(通用)。
有人知道怎么做吗?
#include "jsapi.h"
.....
JSRuntime *rt;
JSContext *cx;
JSObject *global;
/* Create a JS runtime. */
rt = JS_NewRuntime(8L * 1024L * 1024L);
/* Create a context. */
cx = JS_NewContext(rt, 8192);
JS_SetOptions(cx, JSOPTION_VAROBJFIX);
/* Create the global object. */
global = JS_NewObject(cx, &global_class, NULL, NULL);
/* Populate the global object with the standard globals,
like Object and Array. */
if (!JS_InitStandardClasses(cx, global))
@throw [[NSException alloc]initWithName:@"JSerror" reason:@"jserrpr" userInfo:nil];
/* Cleanup. */
JS_DestroyContext(cx);
JS_DestroyRuntime(rt);
JS_ShutDown();
最佳答案
这是一个大致基于原始蜘蛛猴中的示例的示例。
http://egachine.berlios.de/embedding-sm-best-practice/embedding-sm-best-practice.html
我进行了修改,使其可以与多线程一起工作(iMonkey 已启用)。
https://developer.mozilla.org/En/SpiderMonkey/Internals/Thread_Safety
//
// JSEngine.mm
// POC_JS
//
// Created by Quoc Le on 7/12/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "JSEngine.h"
/* get SpiderMonkey API declarations */
#include <jsapi.h>
/* EXIT_FAILURE and EXIT_SUCCESS */
#include <stdlib.h>
/* strlen */
#include <string.h>
@implementation JSEngine
+ (int) run
{
/* pointer to our runtime object */
JSRuntime *runtime=NULL;
/* pointer to our context */
JSContext *context=NULL;
/* pointer to our global JavaScript object */
JSObject *global=NULL;
/* script to run (should return 100) */
char *script="var x=10;x*x;";
/* JavaScript value to store the result of the script */
jsval rval;
/* create new runtime, new context, global object */
if ( (!(runtime = JS_NewRuntime (1024L*1024L)))
|| (!(context = JS_NewContext (runtime, 8192)))
) return EXIT_FAILURE;
JS_SetContextThread(context);
JS_BeginRequest(context);
// || (!(global = JS_NewObject (context, NULL, NULL, NULL)))
global = JS_NewObject (context, NULL, NULL, NULL);
/* set global object of context and initialize standard ECMAScript
objects (Math, Date, ...) within this global object scope */
if (!JS_InitStandardClasses(context, global)) return EXIT_FAILURE;
/* now we are ready to run our script */
if (!JS_EvaluateScript(context, global,script, strlen(script),
"script", 1, &rval))
return EXIT_FAILURE;
/* check if the result is really 100 */
NSLog(@"RSVAL %d", JSVAL_TO_INT(rval));
if (!(JSVAL_IS_INT(rval)&&(JSVAL_TO_INT(rval)==100)))
return EXIT_FAILURE;
JS_EndRequest(context);
JS_ClearContextThread(context);
/* clean up */
//JS_DestroyContext(context);
//JS_DestroyRuntime(runtime);
//JS_ShutDown();
return EXIT_SUCCESS;
}
@end
关于javascript - 如何在 iOS 应用程序中使用 iMonkey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309715/