// V8test. CPP: defines the entry point for the console application. // # include "stdafx. H "# include <v8.h> # pragma comment (Lib," v8_base.lib ") # pragma comment (Lib," v8_snapshot.lib ") # pragma comment (Lib," ws2_32.lib ") # pragma comment (Lib, "winmm. lib ") using namespace V8; int main (INT argc, char * argv []) {// create a stack-allocated handle scope. handlescope handle_scope; // create a new context. handle <context> context = context: New (); // enter the created context for compiling and // running the hello World script. context: Scope context_scope (context); // create a string containing the JavaScript source code. handle <string> source = string: New ("" function myobj () "" {"" this. myarray = [1, 2, 2, 2]; "" this. mydouble = math. pi; ""} "" myobj. prototype. myfunction = function (arg1, arg2) "" {"" Return (this. mydouble + arg1 + arg2); ""}; "" Var globalobject = new myobj (); "); string * STR = * Source; // compile the source code. handle <SCRIPT> script = Script: Compile (source); // run the script to get the result. handle <value> result = script-> Run (); // convert the result to an ASCII string and print it. string: asciivalue ASCII (result); printf ("% s \ n", * ASCII); // get the object using the variable name. The global variable belongs to global () object local <Object> globalobject = Local <Object>: Cast (context-> global ()-> get (string: New ("globalobject "))); // obtain the myarray attribute handle of the globalobject <array> arrayproperty = handle <array>: Cast (globalobject-> get (string: New ("myarray "))); string: asciivalue ascii2 (arrayproperty); printf ("% s \ n", * ascii2 ); // obtain the mydouble attribute handle of the globalobject <Object> doubleproperty = handle <object >:: cast (globalobject-> get (string: New ("mydouble "))); string: asciivalue ascii3 (doubleproperty); printf ("% s \ n", * ascii3 ); // obtain the myfunction attribute local <function> func = Local <function>: Cast (globalobject-> get (string: New ("myfunction") of the globalobject "))); local <value> argv2 [2] = {V8: Number: New (1.123123), V8: Number: New (2.234234 )}; // call the myfunction object string: asciivalue ascii4 (func-> call (globalobject, 2, argv2); printf ("% s \ n", * ascii4 ); // dispose the persistent context. (persistent <context> (context )). dispose (); Return 0 ;}
Running result:
Function (arg1, arg2) {return (this. mydouble + arg1 + arg2);} 1, 2, 2, 2, 23.1415926535897936.498949653589793 press any key to continue...