使用 SpiderMonkey 使 C++應用支持 JavaScript 腳本引擎
翻譯:dozb 英文版
這個教程的目的是演示如何使你的 C++ 應用能夠解釋執行 JavaScript 腳本。
SpiderMonkey
SpiderMonkey, 是 Mozilla 項目的一部分, 是一個執行JavaScript腳本的引擎. 它用 C 實現。還有一個叫做 Rhino的Java版本。
首先你要下載 SpiderMonkey 的最新版本. 下載包是以源代碼形式分發的。這就需要你自己編譯腳本引擎. 對于 Visual C++ 用戶可以在 src-目錄找到工程文件. 編譯結果是叫做 'js32.dll' 的動態庫.
也可以用 SpiderMonkey 在 Macintosh 和 Unix平臺上. 讀 ReadMe.html 來學習在其他平臺如何編譯。
從C++中執行 JavaScript 程序
第1步 - 創建 JavaScript 運行時環境(runtime)
JavaScript 運行時環境是調用 JS_NewRuntime 來初始化. 它分配運行時環境的所需內存。 你要指定所分配的字節數,超過這個大小碎片收集器將運行。
JSRuntime *rt = JS_NewRuntime(1000000L);
if ( rt == NULL )
{
// Do some error reporting
}
第2步 - 創建一個上下文(context)
上下文指定腳本棧的大小, 私有內存的字節數被分配給指定腳本的執行棧. 每個腳本關聯于自己所擁有的上下文。
但上下文被一個腳本或線程使用時,其他腳本或線程不能使用。可當腳本或線程結束,這個上下文就可以被重用于下一個腳本或線程。
用 JS_NewContext 方法創建新的上下文。一個上下文和一個運行時環境關聯,你必須指定棧的大小。
JSContext *cx = JS_NewContext(m_rt, 8192);
if ( cx == NULL )
{
// Do some error reporting
}
第3步 - 初始化全局對象(global object)
在腳本執行前,你必須初始化 general JavaScript 函數和創建用于大多數腳本的 object 類.
全局對象( global object) 用 JSClass 結構來描述. 初始化這個結構如下:
JSClass globalClass =
{
"Global", 0,
JS_PropertyStub, JS_PropertyStub,
JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub
};
現在你可以創建 global object 且初始化它。
JSObject *globalObj = JS_NewObject(cx, &globalClass, 0, 0);
JS_InitStandardClasses(cx, globalObj);
第4步 - 執行腳本
執行腳本的一種途徑是用 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);
當這個腳本運行沒有錯誤, 今天的日期被保存在 rval 中。rval 保存函數最后的執行結果。JS_EvaluateScript的返回值,運行成功是 JS_TRUE,發生錯誤是 JS_FALSE 。
從 rval 取回字符串的值如下所示。 這里就不演示每個細節. 當你需要的時候查看相關 API 的信息。
JSString *str = JS_ValueToString(cx, rval);
std::cout << JS_GetStringBytes(str);
第5步 - 清理腳本引擎
在應用程序結束前, 必須清理腳本引擎.
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類.
創建一個新的 C++ 類,可以源于將在其中使用JavaScript的類,或者創建一個新類有一個那個類類型的成員。
在 JavaScript 中用結構 JSClass 來定義類. 創建一個這個類型的靜態(static)成員. 聲明為 public 成員, 因為這個結構要被其他類使用。它可以被用于其他類來確定對象類型. (參考 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 結構包含 JavaScript 類的名字, 一些標志和 用于引擎回調的函數名. 例如一個回調用于當引擎需要從你的類中獲取一個屬性時。
在C++文件的實現中定義 JSClass 結構,如下所示.
// 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
};
所用的回調是 JSCustomer::JSGetProperty, JSCustomer::JSSetProperty 和 JSCustomer::JSDestructor. JSGetProperty 當引擎獲取屬性時被回調, JSSetProperty 當引擎設置屬性時被回調,JSDestructor 當JavaScript 對象被銷毀時回調。
標志 JSCLASS_HAS_PRIVATE 用于指示引擎開辟內存來綁定數據到 JavaScript 對象. 你可以用 this 存儲一個指向你的類的指針.
回調是C++類的靜態成員函數.
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 對象
創建另一個叫 JSInit 的靜態方法 ,見下例. 這個方法將被應用程序調用,用來創建 JavaScript 運行時環境.
static JSObject *JSInit(JSContext *cx, JSObject *obj, JSObject *proto);
實現代碼如下
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;
}
靜態方法 JSConstructor 當你的對象被腳本實例化的時候被調用. 這個方法非常方便用于綁定你的數據到對象,通過調用 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;
}
這個構造器方法可以有多個參數, 能用于初始化你的類. 現在你已經在堆上創建了一個指針, 你也需要一種途徑銷毀這個指針. 這可以通過靜態方法 JS_Destructor 來完成.
void JSCustomer::JSDestructor(JSContext *cx, JSObject *obj)
{
JSCustomer *p = JS_GetPrivate(cx, obj);
delete p;
p = NULL;
}
第3步 - 增加屬性
增加一個類型為 JSPropertySpec 的靜態數組成員 . 這個數組將包含屬性信息. 再創建一個屬性ID號的枚舉(enum).
static JSPropertySpec customer_properties[];
enum
{
name_prop,
age_prop
};
在實現文件中初始化這個數組,代碼如下
JSPropertySpec JSCustomer::customer_properties[] =
{
{ "name", name_prop, JSPROP_ENUMERATE },
{ "age", age_prop, JSPROP_ENUMERATE },
{ 0 }
};
數組的最后一個元素必須是空(NULL). 每個元素包含另一個有 3 個元素的數組. 第一個元素是名字,將在 JavaScript 腳本中使用。第二個元素是屬性的唯一ID號, 將被傳遞到回調函數中。第三個元素是一個標志,JSPROP_ENUMERATE 表示腳本中當枚舉Customer對象的這個屬性時是可見的,就是可以用在腳本中的for 或 in 語句中. 你可以指定 JSPROP_READONLY 屬性來說明這個屬性是不可以修改的.
現在你能實現獲取(getting)和設置(setting)屬性的回調函數.
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;
}
記得在屬性回調中返回 JS_TRUE . 當你返回 JS_FALSE 將表示在你的對象中沒有發現這個屬性.
第4步 - 增加方法
創建類型為 JSFunctionSpec 的靜態成員數組.
static JSFunctionSpec customer_methods[];
在實現文件中初始化這個數組,代碼如下
JSFunctionSpec wxJSFrame::wxFrame_methods[] =
{
{ "computeReduction", computeReduction, 1, 0, 0 },
{ 0 }
};
數組的最后一個元素必須是空(NULL). 每個元素包含另一個有 5 個元素的數組. 第一個元素是腳本中使用的函數名. 第二個元素是全局或靜態成員函數名. 第三個元素是這個函數的參數個數. 最后兩個元素忽略.
在類中創建一個靜態方法
static JSBool computeReduction(JSContext *cx, JSObject *obj, uintN argc,
jsval *argv, jsval *rval);
當函數成功就返回 JS_TRUE . 否則返回 JS_FALSE. 你的JavaScript方法實際返回值被放到了 rval 參數中.
實現這個方法的例子
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;
}
一個例子
下面的腳本使用上面創建的對象
var c = new Customer();
c.name = "Franky";
c.age = 32;
var reduction = c.computeReduction();
不要忘記當創建上下文的時候初始化 JavaScript 對象:
JSObject *obj = JSCustomer::JSInit(cx, global);
代碼
//main.cpp 演示如何執行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類的實現
/**
* 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();