Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to execute JavaScript program in C++

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to execute JavaScript programs in C++". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

SpiderMonkey

SpiderMonkey is part of the Mozilla project, written in C, and is the engine responsible for executing JavaScript scripts. There is also a Java engine called Rhino.

The latest version of SpiderMonkey can be downloaded here. It is released as source code, so you have to compile it yourself. Visual C++ users can find the Workspace project project file in the src directory to compile, and the compilation results in a dll file called 'js32.dll'.

SpiderMonkey can also be used on Macintosh and Unix.

Execute step 1 of the JavaScript program in C++-create a JavaScript runtime (runtime instance)

Initialize a JavaScript runtime available JS_NewRuntime method, which allocates memory for runtime while specifying a number of bytes that the garbage collector will run automatically when the memory allocation exceeds that number.

JSRuntime * rt = JS_NewRuntime (1000000L)

If (rt = = NULL)

{

/ / Do some error reporting

}

Step 2-create a context (context)

Context indicates the stack size required for the script to run, that is, the amount of private memory allocated to the script execution stack. Each script is associated with its own context.

When a context is being used by a script or thread, other scripts or threads cannot use the context. However, when the script or thread ends, the context can be reused by the next script or thread.

Create a new context with the JS_NewContext method. The context must be associated with a runtime, and the stack size must be specified when calling the JS_NewContext method.

JSContext * cx = JS_NewContext (m_rt, 8192)

If (cx = = NULL)

{

/ / Do some error reporting

}

Step 3-initialize the global object

Before a script can start running, you must initialize some of the generic JavaScript functions and built-in (build-in) class objects that most scripts use.

Global objects are described in a JSClass structure. The structure can be initialized in the following ways:

JSClass globalClass =

{

"Global", 0

JS_PropertyStub, JS_PropertyStub

JS_PropertyStub, JS_PropertyStub

JS_EnumerateStub, JS_ResolveStub

JS_ConvertStub, JS_FinalizeStub

}

Now create and initialize the global object: JSObject * globalObj = JS_NewObject (cx, & globalClass, 0,0); JS_InitStandardClasses (cx, globalObj); step 4-execute the script

One way to execute a script is to use the JS_EvaluateScript method:

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)

In this script, if you run it correctly, the data for the day is saved in rval. Rval contains the result of the last function executed. If JS_EvaluteScript returns JS_TRUE, the execution is successful, and if JS_FALSE is returned, an error has occurred.

To get the corresponding string value from rval, you can use the following method. I don't want to explain all the details here. For more detailed information, please check the API documentation yourself.

JSString * str = JS_ValueToString (cx, rval)

Std::cout setCustomer (new Customer ())

If (! JS_SetPrivate (cx, obj, p))

Return JS_FALSE

* rval = OBJECT_TO_JSVAL (obj)

Return JS_TRUE

}

The JSConstructor constructor can take multiple parameters to initialize the class. So far, you have created a pointer on the heap, and you need a way to destroy it, which can be done through JS_Destructor:

Void JSCustomer::JSDestructor (JSContext * cx, JSObject * obj)

{

JSCustomer * p = JS_GetPrivate (cx, obj)

Delete p

P = NULL

}

Step 3-add attributes

Add an array of static members of type JSPropertySpec to hold the attribute information, while defining the enumerated variables of the property ID.

Static JSPropertySpec customer_properties []

Enum

{

Name_prop

Age_prop

}

Initialize the array in the implementation file as follows:

JSPropertySpec JSCustomer::customer_properties [] =

{

{"name", name_prop, JSPROP_ENUMERATE}

{"age", age_prop, JSPROP_ENUMERATE}

{0}

}

The last element of the array must be empty, where each element is an array with three elements. The first element is the name for JavaScript. The second element is the unique ID of the attribute and will be passed to the callback function. The third element is the flag bit, which the JSPROP_ENUMERATE represents that the script can see when enumerating all the attributes of the Customer object, or you can specify JSPROP_READONLY to indicate that the attribute is not allowed to be changed by the script.

You can now implement the getting and setting callback functions for this property:

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

}

It is recommended that you return JS_TRUE in the callback function of the property. If JS_FALSE is returned, the search will not be performed when the property is not found in the object (script engine).

Step 4-add method

Create an array of static members of type JSFunctionSpec:

Static JSFunctionSpec customer_methods []

Initialize the array in the implementation file as follows:

JSFunctionSpec wxJSFrame::wxFrame_methods [] =

{

{"computeReduction", computeReduction, 1,0,0}

{0}

}

The last element must be empty, where each element is an array of five elements. The first element is the name of the method used for the script. The second is the name of a global or static member function. The third is the number of parameters of the method. The last two can be ignored.

Create a static method in the class:

Static JSBool computeReduction (JSContext * cx, JSObject * obj, uintN argc

Jsval * argv, jsval * rval)

This function returns JS_TRUE if it succeeds, JS_FALSE otherwise. Notice that the return value of the real JavaScript method is saved in the rval parameter.

An implementation example of this method:

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

}

Use examples

The following script uses the object you created earlier:

Var c = new Customer ()

C.name = "Franky"

C.age = 32

Var reduction = c.computeReduction ()

Don't forget to initialize the JavaScript object when you create the context:

JSObject * obj = JSCustomer::JSInit (cx, global)

This is the end of the content of "how to execute JavaScript programs in C++". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report