spidermonkey的使用及代码(SpiderMonkey1.7)[通俗易懂]

发布时间:2025-12-09 13:41:29 浏览次数:4

参见https://blog.csdn.net/kaitiren/article/details/21961235
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_User_Guide
https://blog.csdn.net/jnstone3/article/details/3953203?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

http://ftp.mozilla.org/pub/mozilla.org/js/js-1.60.tar.gz

其中,dll. lib使用如下的资源:https://download.csdn.net/download/chenshuanj/2876998?ops_request_misc=&request_id=&biz_id=&utm_source=distribute.pc_search_result.none-task

https://download.csdn.net/download/ecaifu800/6042077?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158452433919726869064130%2522%252C%2522scm%2522%253A%252220140713.130062587..%2522%257D&request_id=158452433919726869064130&biz_id=1&utm_source=distribute.pc_search_result.none-task
下面是代码的整理:

使用示例1:

Customer.h:

#ifndef _Customer_H#define _Customer_H#include <iostream>class Customer{public:Customer() {}Customer(std::string name, int age);int GetAge();void SetAge(int newAge);std::string GetName();void SetName(std::string newName);private:int m_age;std::string m_name;};#endif

Customer.cpp:

#include "Customer.h"Customer::Customer(std::string name, int age) { m_name = name; m_age = age; }int Customer::GetAge() { return m_age;}void Customer::SetAge(int newAge) { m_age = newAge; }std::string Customer::GetName() { return m_name;}void Customer::SetName(std::string newName){ m_name = newName;}

JSCustomer.h:

#pragma once#ifndef _JSCustomer_H#define _JSCustomer_H#include <stdio.h>#include <tchar.h>#include <iostream>#define XP_WIN#include "jsapi.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; }private:Customer *m_pCustomer;static JSPropertySpec Customer_properties[];static JSFunctionSpec Customer_methods[];enum { name_prop, age_prop };};#endif //_JSCustomer_H

JSCustomer.cpp:

#include "JSCustomer.h"#include <string>#define XP_WIN#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);//为js中的内容 wuyifancustomer->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);int gage = p->getCustomer()->GetAge();if (gage < 25)*rval = INT_TO_JSVAL(10);else*rval = INT_TO_JSVAL(5);return JS_TRUE;}

调用代码main.cpp:

// masterTest.cpp : 定义控制台应用程序的入口点。//#include <string.h> //for strlen#include <stdio.h>#include "stdlib.h"#include "string.h"#define XP_WIN#include "jsapi.h"//参见 https://blog.csdn.net/rjs123/article/details/8995344 #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[]){int a = 9;/*if (argc < 2){std::cout << "JSExec usage" << std::endl<< "------------" << std::endl<< "JSExec <fileName>" << std::endl;}*/std::string script;std::string buffer;std::ifstream istr("E:/NLP/dicGenerator/masterTest/example.js");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//JSBool ok = JSCustomer::JSConstructor(cx, globalObj, 0, NULL, NULL);JSObject *newProtoObj = JSCustomer::JSInit(cx, globalObj);// Execute the scriptjsval rval;uintN lineno = 0;JSString *str;JSBool ok = JS_EvaluateScript(cx, globalObj, script.c_str(),script.length(), "E:/NLP/dicGenerator/masterTest/example.js"/*argv[1]*/, lineno, &rval);if (ok == JS_TRUE){str = JS_ValueToString(cx, rval);char *s = JS_GetStringBytes(str);std::cout << "JSExec result:" << s << std::endl;}else{std::cout << "JSExec error" << 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";}}

example.js:

var c = new Customer();c.name = "wuyifan";c.age = 32;var reduction = c.computeReduction();

使用示例2:

test4.cpp:

// masterTest.cpp : 定义控制台应用程序的入口点。//#include <string.h> //for strlen#include <stdio.h>#include "stdlib.h"#include "string.h"#define XP_WIN#include "jsapi.h"//参见 https://blog.csdn.net/rjs123/article/details/8995344 #include <string>#include <iostream>#include <fstream>static JSBool PeoplePrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);JSBool JsFileExecute(JSContext *ctx, const char *file);int usage(const char *progname);typedef struct{char name[16];char addr[64];char tel[10];}PeopleInfo;static PeopleInfo pinfo = { "wuyifang", "beijing", "521521" };JSClass global_class = {"global",0,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS};static JSClass PeopleClass = {"people",0,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS};static JSFunctionSpec PeopleMethods[] = {{ "print", PeoplePrint, 0, 0, 0 },{ NULL }};int main(int argc, char **argv){JSRuntime *rt;JSContext *cx;JSObject *globalObj, *PeopleObj;char *file = NULL;/*if (argc < 2){usage(argv[0]);}else{file = argv[1];}*/file = "E:/NLP/dicGenerator/masterTest/test4.js";rt = JS_NewRuntime(1024L * 1024L);if (!rt)return -1;cx = JS_NewContext(rt, 8L * 1024L);if (!cx)return -1;if (!(globalObj = JS_NewObject(cx, &global_class, NULL, NULL)))return -1;JS_InitStandardClasses(cx, globalObj);PeopleObj = JS_DefineObject(cx, globalObj, "people", &PeopleClass, 0, JSPROP_ENUMERATE);JS_DefineFunctions(cx, PeopleObj, PeopleMethods);if (JsFileExecute(cx, file)){//printf("File execute successfully./n");}else{printf("File execute failed./n");}JS_DestroyContext(cx);JS_DestroyRuntime(rt);return 0;}static JSBool PeoplePrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval){fprintf(stdout, "My Name is %s./nMy Addr is %s./nMy telephone is %s/n", pinfo.name, pinfo.addr, pinfo.tel);return JS_TRUE;}JSBool JsFileExecute(JSContext *ctx, const char *file){JSScript *script = NULL;JSBool retval;jsval ret;JSObject *global = JS_GetGlobalObject(ctx);script = JS_CompileFile(ctx, global, file);if (script == NULL){return JS_FALSE;}retval = JS_ExecuteScript(ctx, global, script, &ret);JS_DestroyScript(ctx, script);return retval;}int usage(const char *progname){printf("Usage: %s <file>/n", progname);exit(-1);}

test4.js:

people.print();

结果:

My Name is wuyifang./nMy Addr is beijing./nMy telephone is 521521/n

使用示例3:

test5.cpp:

#include <string.h> //for strlen#include <stdio.h>#include "stdlib.h"#include "string.h"#define XP_WIN#include "jsapi.h"//参见 https://blog.csdn.net/rjs123/article/details/8995344 #include <string>#include <iostream>#include <fstream>enum PEOPLE { NAME, ADDRESS, TEL };static JSBool GetPeopleProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);static JSBool SetPeopleProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);static JSBool PeoplePrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);enum UNDER { TYPE, PLACE };static JSBool GetUnderProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);static JSBool SetUnderProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp);static JSBool UnderPrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);static void JsErrorHandler(JSContext *ctx, const char *msg, JSErrorReport *er);int usage(const char *progname);JSBool JsFileExecute(JSContext *ctx, const char *file);typedef struct{char name[16];char addr[64];char tel[10];}PeopleInfo;static PeopleInfo pinfo = { "xufeng", "Chongqing", "123456" };typedef struct{char type[16];char place[64];}under_struct;static under_struct under_1 = { "navigate", "Chongqing"};JSClass global_class = {"global",0,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_PropertyStub,JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS};static JSClass PeopleClass = {"people",0,JS_PropertyStub,JS_PropertyStub,GetPeopleProperty,SetPeopleProperty,JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS};static JSClass UnderClass = {"under",0,JS_PropertyStub,JS_PropertyStub,GetPeopleProperty,SetPeopleProperty,JS_EnumerateStub,JS_ResolveStub,JS_ConvertStub,JS_FinalizeStub,JSCLASS_NO_OPTIONAL_MEMBERS};static JSPropertySpec PeopleProperties[] = {{ "name", NAME, JSPROP_ENUMERATE },{ "address", ADDRESS, JSPROP_ENUMERATE },{ "tel", TEL, JSPROP_ENUMERATE },{ NULL }};static JSPropertySpec UnderProperties[] = {{ "type", NAME, JSPROP_ENUMERATE },{ "place", ADDRESS, JSPROP_ENUMERATE },{ NULL }};static JSFunctionSpec PeopleMethods[] = {{ "print", PeoplePrint, 0, 0, 0 },{ NULL }};static JSFunctionSpec UnderMethods[] = {{ "Undeprint", UnderPrint, 0, 0, 0 },{ NULL }};int main(int argc, char **argv){JSRuntime *rt;JSContext *cx;JSObject *globalObj, *PeopleObj,*UnderObj;char *file = NULL;/*if (argc < 2){usage(argv[0]);}else{file = argv[1];}*/file = "E:/NLP/dicGenerator/masterTest/test5.js";rt = JS_NewRuntime(1024L * 1024L);if (!rt)return -1;cx = JS_NewContext(rt, 8L * 1024L);if (!cx)return -1;JS_SetErrorReporter(cx, JsErrorHandler);if (!(globalObj = JS_NewObject(cx, &global_class, NULL, NULL)))return -1;JS_InitStandardClasses(cx, globalObj);/*PeopleObj = JS_DefineObject(cx, globalObj, "people", &PeopleClass, 0, JSPROP_ENUMERATE);JS_DefineProperties(cx, PeopleObj, PeopleProperties);JS_DefineFunctions(cx, PeopleObj, PeopleMethods);*/UnderObj = JS_DefineObject(cx, globalObj, "under", &UnderClass, 0, JSPROP_ENUMERATE);JS_DefineProperties(cx, UnderObj, UnderProperties);JS_DefineFunctions(cx, UnderObj, UnderMethods);if (JsFileExecute(cx, file)){printf("File execute successfully./n");}else{printf("File execute failed./n");}JS_DestroyContext(cx);JS_DestroyRuntime(rt);return 0;}static void JsErrorHandler(JSContext *ctx, const char *msg, JSErrorReport *er){printf("JS Error: %s/nFile: %s:%u/n", msg, er->filename, er->lineno);}static JSBool GetPeopleProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp){if (JSVAL_IS_INT(id)) {switch (JSVAL_TO_INT(id)) {case NAME:*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pinfo.name));//xufeng的内容break;case ADDRESS:*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pinfo.addr));//Chongqing的内容break;case TEL:*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, pinfo.tel));//123456的内容break;}}return JS_TRUE;}static JSBool GetUnderProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp){if (JSVAL_IS_INT(id)) {switch (JSVAL_TO_INT(id)) {case TYPE:*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, under_1.type));//xufeng的内容break;case PLACE:*vp = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, under_1.place));//Chongqing的内容break;}}return JS_TRUE;}static JSBool SetPeopleProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp){if (JSVAL_IS_INT(id)) {switch (JSVAL_TO_INT(id)) {case NAME:strncpy(pinfo.name, JS_GetStringBytes(JS_ValueToString(cx, *vp)), 15);//从js中取值break;case ADDRESS:strncpy(pinfo.addr, JS_GetStringBytes(JS_ValueToString(cx, *vp)), 63);break;case TEL:strncpy(pinfo.tel, JS_GetStringBytes(JS_ValueToString(cx, *vp)), 9);break;}}return JS_TRUE;}static JSBool SetUnderProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp){if (JSVAL_IS_INT(id)) {switch (JSVAL_TO_INT(id)) {case TYPE:strncpy(under_1.type, JS_GetStringBytes(JS_ValueToString(cx, *vp)), 100);//从js中取值break;case PLACE:strncpy(under_1.place, JS_GetStringBytes(JS_ValueToString(cx, *vp)), 100);break;}}return JS_TRUE;}static JSBool PeoplePrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval){fprintf(stdout, "[PeoplePrint] My Name is %s./nMy Addr is %s./nMy telephone is %s/n", pinfo.name, pinfo.addr, pinfo.tel);return JS_TRUE;}static JSBool UnderPrint(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval){fprintf(stdout, "[UndePrint]  My Name is %s./nMy Addr is %s./n", under_1.type, under_1.place);return JS_TRUE;}int usage(const char *progname){printf("Usage: %s <file>/n", progname);exit(-1);}JSBool JsFileExecute(JSContext *ctx, const char *file){JSScript *script = NULL;JSBool retval;jsval ret;JSObject *global = JS_GetGlobalObject(ctx);    //test begin 换一种方法,直接读取JS文件后放入内存buf中进行分析,得到的结果是一样的,这样的话,可以动态添加js文件的内容FILE* fp;char buf[102400 * 5];JSString* jss;if (!(fp = fopen("E:/NLP/dicGenerator/masterTest/test5.js", "r"))) return 0;int len = fread(buf, 1, 102400 * 5, fp);fclose(fp);if (len <= 0)return 0;jsval rval;JS_EvaluateScript(ctx, global, buf, len, "script", 1, &rval);jss = JS_ValueToString(ctx, rval);printf("The result is: %s\n", JS_GetStringBytes(jss));//test end 换一种方法,直接读取JS文件后放入内存buf中进行分析,得到的结果是一样的,这样的话,可以动态添加js文件的内容script = JS_CompileFile(ctx, global, file);if (script == NULL){return JS_FALSE;}retval = JS_ExecuteScript(ctx, global, script, &ret);JSString *str = JS_ValueToString(ctx, ret);char * poutStr = JS_GetStringBytes(str);JS_DestroyScript(ctx, script);return retval;}

test5.js:

//people.print();//调用的是c++中函数:people.print();输出是xufeng的信息//people.name = "wuyifan-js";//调用的是c++中函数:SetPeopleProperty//people.address = "Beijing-js";//调用的是c++中函数:SetPeopleProperty//people.tel = "521521";//调用的是c++中函数:SetPeopleProperty//people.print();//输出wuyifan-js的信息function InitParam(a, b){return a+b;}function GetEntryForm(under){//return "abcdefg"//consolelog(under.type);var result = under;switch(under.type){case 'test'://导航var stype = result.type ;var splace = result.place ;var addab = InitParam(stype, splace)rts = '[Return]:{"ziduanyi":"neirongyi","again":0,"result":{"data":{"content":"' + stype + '","Con_name":"' + splace + addab+'"},"status":"success","operationType":"nihao"}}';return rts;break;default:break;}}under.Undeprint();under.type = "test";under.place = "shanghai";var retVl = GetEntryForm(under);GetEntryForm(under);

结果:

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477