使用 SpiderMonkey 使 C++應(yīng)用支持 JavaScript 腳本引擎
使用 SpiderMonkey 使 C++應(yīng)用支持 JavaScript 腳本引擎
翻譯:dozb 英文版
這個(gè)教程的目的是演示如何使你的 C++ 應(yīng)用能夠解釋執(zhí)行 JavaScript 腳本。
SpiderMonkey
SpiderMonkey, 是 Mozilla 項(xiàng)目的一部分, 是一個(gè)執(zhí)行JavaScript腳本的引擎. 它用 C 實(shí)現(xiàn)。還有一個(gè)叫做 Rhino的Java版本。
首先你要下載 SpiderMonkey 的最新版本. 下載包是以源代碼形式分發(fā)的。這就需要你自己編譯腳本引擎. 對(duì)于 Visual C++ 用戶可以在 src-目錄找到工程文件. 編譯結(jié)果是叫做 'js32.dll' 的動(dòng)態(tài)庫(kù).
也可以用 SpiderMonkey 在 Macintosh 和 Unix平臺(tái)上. 讀 ReadMe.html 來(lái)學(xué)習(xí)在其他平臺(tái)如何編譯。
從C++中執(zhí)行 JavaScript 程序
第1步 - 創(chuàng)建 JavaScript 運(yùn)行時(shí)環(huán)境(runtime)
JavaScript 運(yùn)行時(shí)環(huán)境是調(diào)用 JS_NewRuntime 來(lái)初始化. 它分配運(yùn)行時(shí)環(huán)境的所需內(nèi)存。 你要指定所分配的字節(jié)數(shù),超過(guò)這個(gè)大小碎片收集器將運(yùn)行。
JSRuntime *rt = JS_NewRuntime(1000000L);
if ( rt == NULL )
{
// Do some error reporting
}
第2步 - 創(chuàng)建一個(gè)上下文(context)
上下文指定腳本棧的大小, 私有內(nèi)存的字節(jié)數(shù)被分配給指定腳本的執(zhí)行棧. 每個(gè)腳本關(guān)聯(lián)于自己所擁有的上下文。
但上下文被一個(gè)腳本或線程使用時(shí),其他腳本或線程不能使用。可當(dāng)腳本或線程結(jié)束,這個(gè)上下文就可以被重用于下一個(gè)腳本或線程。
用 JS_NewContext 方法創(chuàng)建新的上下文。一個(gè)上下文和一個(gè)運(yùn)行時(shí)環(huán)境關(guān)聯(lián),你必須指定棧的大小。
JSContext *cx = JS_NewContext(m_rt, 8192);
if ( cx == NULL )
{
// Do some error reporting
}
第3步 - 初始化全局對(duì)象(global object)
在腳本執(zhí)行前,你必須初始化 general JavaScript 函數(shù)和創(chuàng)建用于大多數(shù)腳本的 object 類.
全局對(duì)象( global object) 用 JSClass 結(jié)構(gòu)來(lái)描述. 初始化這個(gè)結(jié)構(gòu)如下:
JSClass globalClass =
{
"Global", 0,
JS_PropertyStub, JS_PropertyStub,
JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub
};
現(xiàn)在你可以創(chuàng)建 global object 且初始化它。
JSObject *globalObj = JS_NewObject(cx, &globalClass, 0, 0); JS_InitStandardClasses(cx, globalObj);
第4步 - 執(zhí)行腳本
執(zhí)行腳本的一種途徑是用 JS_EvaluateScript 方法.
std::string script = "var today = Date(); today.toString();"
jsval rval;
uintN lineno = 0;
JSBool ok = JS_EvaluateScript(cx, globalObj, script.c_str(),
script.length(), "script", lineno, &rval);
當(dāng)這個(gè)腳本運(yùn)行沒(méi)有錯(cuò)誤, 今天的日期被保存在 rval 中。rval 保存函數(shù)最后的執(zhí)行結(jié)果。JS_EvaluateScript的返回值,運(yùn)行成功是 JS_TRUE,發(fā)生錯(cuò)誤是 JS_FALSE 。
從 rval 取回字符串的值如下所示。 這里就不演示每個(gè)細(xì)節(jié). 當(dāng)你需要的時(shí)候查看相關(guān) API 的信息。
JSString *str = JS_ValueToString(cx, rval); std::cout << JS_GetStringBytes(str);
第5步 - 清理腳本引擎
在應(yīng)用程序結(jié)束前, 必須清理腳本引擎.
JS_DestroyContext(cx);
JS_DestroyRuntime(rt);
在 C++ 中定義 JavaScript 類
在例子中使用的類如下:
class Customer
{
public:
int GetAge() { return m_age; }
void SetAge(int newAge) { m_age = newAge; }
std::string GetName() { return m_name; }
void SetName(std::string newName) { m_name = newName; }
private:
int m_age;
std::string m_name;
};
第1步 - JavaScript類.
創(chuàng)建一個(gè)新的 C++ 類,可以源于將在其中使用JavaScript的類,或者創(chuàng)建一個(gè)新類有一個(gè)那個(gè)類類型的成員。
在 JavaScript 中用結(jié)構(gòu) JSClass 來(lái)定義類. 創(chuàng)建一個(gè)這個(gè)類型的靜態(tài)(static)成員. 聲明為 public 成員, 因?yàn)檫@個(gè)結(jié)構(gòu)要被其他類使用。它可以被用于其他類來(lái)確定對(duì)象類型. (參考 JS_InstanceOf API)
// JSCustomer.h
class JSCustomer
{
public:
JSCustomer() : m_pCustomer(NULL)
{
}
~JSCustomer()
{
delete m_pCustomer;
m_pCustomer = NULL;
}
static JSClass customerClass;
protected:
void setCustomer(Customer *customer)
{
m_pCustomer = customer;
}
Customer* getCustomer()
{
return m_pCustomer;
}
private:
Customer *m_pCustomer;
};
JSClass 結(jié)構(gòu)包含 JavaScript 類的名字, 一些標(biāo)志和 用于引擎回調(diào)的函數(shù)名. 例如一個(gè)回調(diào)用于當(dāng)引擎需要從你的類中獲取一個(gè)屬性時(shí)。
在C++文件的實(shí)現(xiàn)中定義 JSClass 結(jié)構(gòu),如下所示.
// JSCustomer.cpp
JSClass JSCustomer::customerClass =
{
"Customer", JSCLASS_HAS_PRIVATE,
JS_PropertyStub, JS_PropertyStub,
JSCustomer::JSGetProperty, JSCustomer::JSSetProperty,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JSCustomer::JSDestructor
};
所用的回調(diào)是 JSCustomer::JSGetProperty, JSCustomer::JSSetProperty 和 JSCustomer::JSDestructor. JSGetProperty 當(dāng)引擎獲取屬性時(shí)被回調(diào), JSSetProperty 當(dāng)引擎設(shè)置屬性時(shí)被回調(diào),JSDestructor 當(dāng)JavaScript 對(duì)象被銷毀時(shí)回調(diào)。
標(biāo)志 JSCLASS_HAS_PRIVATE 用于指示引擎開(kāi)辟內(nèi)存來(lái)綁定數(shù)據(jù)到 JavaScript 對(duì)象. 你可以用 this 存儲(chǔ)一個(gè)指向你的類的指針.
回調(diào)是C++類的靜態(tài)成員函數(shù).
static JSBool JSGetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
static JSBool JSSetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
static JSBool JSConstructor(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval);
static void JSDestructor(JSContext *cx, JSObject *obj);
第2步 - 初始化 JavaScript 對(duì)象
創(chuàng)建另一個(gè)叫 JSInit 的靜態(tài)方法 ,見(jiàn)下例. 這個(gè)方法將被應(yīng)用程序調(diào)用,用來(lái)創(chuàng)建 JavaScript 運(yùn)行時(shí)環(huán)境.
static JSObject *JSInit(JSContext *cx, JSObject *obj, JSObject *proto);
實(shí)現(xiàn)代碼如下
JSObject *JSCustomer::JSInit(JSContext *cx, JSObject *obj, JSObject *proto)
{
JSObject *newObj = JS_InitClass(cx, obj, proto, &customerClass,
JSCustomer::JSConstructor, 0,
JSCustomer::customer_properties, JSCustomer::customer_methods,
NULL, NULL);
return newObj;
}
靜態(tài)方法 JSConstructor 當(dāng)你的對(duì)象被腳本實(shí)例化的時(shí)候被調(diào)用. 這個(gè)方法非常方便用于綁定你的數(shù)據(jù)到對(duì)象,通過(guò)調(diào)用 JS_SetPrivate API.
JSBool JSCustomer::JSConstructor(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval)
{
JSCustomer *p = new JSCustomer();
p->setCustomer(new Customer());
if ( ! JS_SetPrivate(cx, obj, p) )
return JS_FALSE;
*rval = OBJECT_TO_JSVAL(obj);
return JS_TRUE;
}
這個(gè)構(gòu)造器方法可以有多個(gè)參數(shù), 能用于初始化你的類. 現(xiàn)在你已經(jīng)在堆上創(chuàng)建了一個(gè)指針, 你也需要一種途徑銷毀這個(gè)指針. 這可以通過(guò)靜態(tài)方法 JS_Destructor 來(lái)完成.
void JSCustomer::JSDestructor(JSContext *cx, JSObject *obj)
{
JSCustomer *p = JS_GetPrivate(cx, obj);
delete p;
p = NULL;
}
第3步 - 增加屬性
增加一個(gè)類型為 JSPropertySpec 的靜態(tài)數(shù)組成員 . 這個(gè)數(shù)組將包含屬性信息. 再創(chuàng)建一個(gè)屬性ID號(hào)的枚舉(enum).
static JSPropertySpec customer_properties[];
enum
{
name_prop,
age_prop
};
在實(shí)現(xiàn)文件中初始化這個(gè)數(shù)組,代碼如下
JSPropertySpec JSCustomer::customer_properties[] =
{
{ "name", name_prop, JSPROP_ENUMERATE },
{ "age", age_prop, JSPROP_ENUMERATE },
{ 0 }
};
數(shù)組的最后一個(gè)元素必須是空(NULL). 每個(gè)元素包含另一個(gè)有 3 個(gè)元素的數(shù)組. 第一個(gè)元素是名字,將在 JavaScript 腳本中使用。第二個(gè)元素是屬性的唯一ID號(hào), 將被傳遞到回調(diào)函數(shù)中。第三個(gè)元素是一個(gè)標(biāo)志,JSPROP_ENUMERATE 表示腳本中當(dāng)枚舉Customer對(duì)象的這個(gè)屬性時(shí)是可見(jiàn)的,就是可以用在腳本中的for 或 in 語(yǔ)句中. 你可以指定 JSPROP_READONLY 屬性來(lái)說(shuō)明這個(gè)屬性是不可以修改的.
現(xiàn)在你能實(shí)現(xiàn)獲取(getting)和設(shè)置(setting)屬性的回調(diào)函數(shù).
JSBool JSCustomer::JSGetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
if (JSVAL_IS_INT(id))
{
Customer *priv = (Customer *) JS_GetPrivate(cx, obj);
switch(JSVAL_TO_INT(id))
{
case name_prop:
break;
case age_prop:
*vp = INT_TO_JSVAL(priv->getCustomer()->GetAge());
break;
}
}
return JS_TRUE;
}
JSBool JSCustomer::JSSetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
{
if (JSVAL_IS_INT(id))
{
Customer *priv = (Customer *) JS_GetPrivate(cx, obj);
switch(JSVAL_TO_INT(id))
{
case name_prop:
break;
case age_prop:
priv->getCustomer()->SetAge(JSVAL_TO_INT(*vp));
break;
}
}
return JS_TRUE;
}
記得在屬性回調(diào)中返回 JS_TRUE . 當(dāng)你返回 JS_FALSE 將表示在你的對(duì)象中沒(méi)有發(fā)現(xiàn)這個(gè)屬性.
第4步 - 增加方法
創(chuàng)建類型為 JSFunctionSpec 的靜態(tài)成員數(shù)組.
static JSFunctionSpec customer_methods[];
在實(shí)現(xiàn)文件中初始化這個(gè)數(shù)組,代碼如下
JSFunctionSpec wxJSFrame::wxFrame_methods[] =
{
{ "computeReduction", computeReduction, 1, 0, 0 },
{ 0 }
};
數(shù)組的最后一個(gè)元素必須是空(NULL). 每個(gè)元素包含另一個(gè)有 5 個(gè)元素的數(shù)組. 第一個(gè)元素是腳本中使用的函數(shù)名. 第二個(gè)元素是全局或靜態(tài)成員函數(shù)名. 第三個(gè)元素是這個(gè)函數(shù)的參數(shù)個(gè)數(shù). 最后兩個(gè)元素忽略.
在類中創(chuàng)建一個(gè)靜態(tài)方法
static JSBool computeReduction(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval);
當(dāng)函數(shù)成功就返回 JS_TRUE . 否則返回 JS_FALSE. 你的JavaScript方法實(shí)際返回值被放到了 rval 參數(shù)中.
實(shí)現(xiàn)這個(gè)方法的例子
JSBool JSCustomer::computeReduction(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval)
{
JSCustomer *p = JS_GetPrivate(cx, obj);
if ( p->getCustomer()->GetAge() < 25 )
*rval = INT_TO_JSVAL(10);
else
*rval = INT_TO_JSVAL(5);
return JS_TRUE;
}
一個(gè)例子
下面的腳本使用上面創(chuàng)建的對(duì)象
var c = new Customer(); c.name = "Franky"; c.age = 32; var reduction = c.computeReduction();
不要忘記當(dāng)創(chuàng)建上下文的時(shí)候初始化 JavaScript 對(duì)象:
JSObject *obj = JSCustomer::JSInit(cx, global);
代碼
//main.cpp 演示如何執(zhí)行javascript
#define XP_PC
#include <string>
#include <iostream>
#include <fstream>
#include <jsapi.h>
#include "JSCustomer.h"
JSClass globalClass =
{
"Global", 0,
JS_PropertyStub, JS_PropertyStub,JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub
};
void main(int argc, char *argv[])
{
if ( argc < 2 )
{
std::cout << "JSExec usage" << std::endl
<< "------------" << std::endl
<< "JSExec <fileName>" << std::endl;
}
std::string script;
std::string buffer;
std::ifstream istr(argv[1]);
if ( istr.is_open() )
{
do
{
std::getline(istr, buffer);
script += buffer;
} while (!istr.fail());
}
else
{
std::cout << "JSExec error" << std::endl
<< "------------" << std::endl
<< "Can't open scriptfile " << argv[1] << std::endl;
exit(0);
}
JSRuntime *rt = JS_Init(1000000L);
if ( rt )
{
JSContext *cx = JS_NewContext(rt, 8192);
if ( cx )
{
JSObject *globalObj = JS_NewObject(cx, &globalClass, 0, 0);
if ( globalObj )
{
JS_InitStandardClasses(cx, globalObj);
// Init JSCustomer
JSCustomer::JSInit(cx, globalObj);
// Execute the script
jsval rval;
uintN lineno = 0;
JSString *str;
JSBool ok = JS_EvaluateScript(cx, globalObj, script.c_str(), script.length(), argv[1], lineno, &rval);
if ( ok == JS_TRUE )
{
str = JS_ValueToString(cx, rval);
char *s = JS_GetStringBytes(str);
std::cout << "JSExec result" << std::endl
<< "-------------" << std::endl
<< s << std::endl;
}
else
{
std::cout << "JSExec error" << std::endl
<< "------------" << std::endl
<< "Error in JavaScript file " << argv[1] << std::endl;
}
}
else
{
std::cout << "Unable to create the global object";
}
JS_DestroyContext(cx);
}
else
{
std::cout << "Unable to create a context";
}
JS_Finish(rt);
}
else
{
std::cout << "Unable to initialize the JavaScript Engine";
}
}
//JSCustomer.h 演示Customer JavaScript類的定義
/**
* JSCustomer.h - Example for my tutorial : Scripting C++ with JavaScript
* (c) 2002 - Franky Braem
* http://www.braem17.yucom.be
*/
#ifndef _JSCustomer_H
#define _JSCustomer_H
#include "Customer.h"
class JSCustomer
{
public:
/**
* Constructor
*/
JSCustomer() : m_pCustomer(NULL)
{
}
/**
* Destructor
*/
virtual ~JSCustomer()
{
delete m_pCustomer;
m_pCustomer = NULL;
}
/**
* JSGetProperty - Callback for retrieving properties
*/
static JSBool JSGetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
/**
* JSSetProperty - Callback for setting properties
*/
static JSBool JSSetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);
/**
* JSConstructor - Callback for when a wxCustomer object is created
*/
static JSBool JSConstructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
/**
* JSDestructor - Callback for when a wxCustomer object is destroyed
*/
static void JSDestructor(JSContext *cx, JSObject *obj);
/**
* JSInit - Create a prototype for wxCustomer
*/
static JSObject* JSInit(JSContext *cx, JSObject *obj, JSObject *proto = NULL);
static JSBool computeReduction(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
static JSClass Customer_class;
void setCustomer(Customer *customer)
{
m_pCustomer = customer;
}
Customer* getCustomer()
{
return m_pCustomer;
}
protected:
private:
Customer *m_pCustomer;
static JSPropertySpec Customer_properties[];
static JSFunctionSpec Customer_methods[];
enum
{
name_prop,
age_prop
};
};
#endif //_JSCustomer_H
//JSCustomer.cpp 演示JSCustomer類的實(shí)現(xiàn)
/**
* JSCustomer.cpp - Example for my tutorial : Scripting C++ with JavaScript
* (c) 2002 - Franky Braem
* http://www.braem17.yucom.be
*/
#include <string>
#define XP_PC
#include <jsapi.h>
//#include "Customer.h"
#include "JSCustomer.h"
JSPropertySpec JSCustomer::Customer_properties[] =
{
{ "name", name_prop, JSPROP_ENUMERATE },
{ "age", age_prop, JSPROP_ENUMERATE },
{ 0 }
};
JSFunctionSpec JSCustomer::Customer_methods[] =
{
{ "computeReduction", computeReduction, 1, 0, 0 },
{ 0, 0, 0, 0, 0 }
};
JSClass JSCustomer::Customer_class =
{
"Customer", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub,
JSCustomer::JSGetProperty, JSCustomer::JSSetProperty,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JSCustomer::JSDestructor
};
JSBool JSCustomer::JSGetProperty(JSContext *cx, JSObject *obj, jsval id,
jsval *vp)
{
if (JSVAL_IS_INT(id))
{
JSCustomer *p = (JSCustomer *) JS_GetPrivate(cx, obj);
Customer *customer = p->getCustomer();
switch (JSVAL_TO_INT(id))
{
case name_prop:
{
std::string name = customer->GetName();
JSString *str = JS_NewStringCopyN(cx, name.c_str(), name.length());
*vp = STRING_TO_JSVAL(str);
break;
}
case age_prop:
*vp = INT_TO_JSVAL(customer->GetAge());
break;
}
}
return JS_TRUE;
}
JSBool JSCustomer::JSSetProperty(JSContext *cx, JSObject *obj, jsval id,
jsval *vp)
{
if (JSVAL_IS_INT(id))
{
JSCustomer *p = (JSCustomer *) JS_GetPrivate(cx, obj);
Customer *customer = p->getCustomer();
switch (JSVAL_TO_INT(id))
{
case name_prop:
{
JSString *str = JS_ValueToString(cx, *vp);
std::string name = JS_GetStringBytes(str);
customer->SetName(name);
break;
}
case age_prop:
customer->SetAge(JSVAL_TO_INT(*vp));
break;
}
}
return JS_TRUE;
}
JSBool JSCustomer::JSConstructor(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval)
{
JSCustomer *priv = new JSCustomer();
priv->setCustomer(new Customer());
JS_SetPrivate(cx, obj, (void *) priv);
return JS_TRUE;
}
void JSCustomer::JSDestructor(JSContext *cx, JSObject *obj)
{
JSCustomer *priv = (JSCustomer*) JS_GetPrivate(cx, obj);
delete priv;
priv = NULL;
}
JSObject *JSCustomer::JSInit(JSContext *cx, JSObject *obj, JSObject *proto)
{
JSObject *newProtoObj = JS_InitClass(cx, obj, proto, &Customer_class,
JSCustomer::JSConstructor, 0,
NULL, JSCustomer::Customer_methods,
NULL, NULL);
JS_DefineProperties(cx, newProtoObj, JSCustomer::Customer_properties);
return newProtoObj;
}
JSBool JSCustomer::computeReduction(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval)
{
JSCustomer *p = (JSCustomer*) JS_GetPrivate(cx, obj);
if ( p->getCustomer()->GetAge() < 25 )
*rval = INT_TO_JSVAL(10);
else
*rval = INT_TO_JSVAL(5);
return JS_TRUE;
}
//Customer.h 演示Customer C++類的定義
#ifndef _Customer_H
#define _Customer_H
class Customer
{
public:
int GetAge()
{
return m_age;
}
void SetAge(int newAge)
{
m_age = newAge;
}
std::string GetName()
{
return m_name;
}
void SetName(std::string newName)
{
m_name = newName;
}
private:
int m_age;
std::string m_name;
};
#endif//example.js 演示JavaScript的例子 var c = new Customer(); c.name = "Franky"; c.age = 32; c.computeReduction();
posted on 2011-07-22 16:05 楊粼波 閱讀(2370) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C++

