V8/A Simple Application
From Create Wiki
//note: this particular example is borrowed very closely from V8's embedder's //guide, a definite recommended read that gives a good overview of V8 that //might make many things that I gloss over more clear. #include <iostream> #include <v8.h> //all v8 classes are under the v8 namespace. As I would get tired of typing it //over and over again, let's just say "using namespace" using namespace v8; int main (int argc, char * const argv[]) { //this is all about memory. We'll get into that later. HandleScope handle_scope; //Create a context for the script to run in. For now, consider this a Nike //statement: just do it. Later, we'll go over the details of why in [[v8/Contexts]]. //also take note of, but simultaneously ignore the obtrusive template class //named persistent. It's a handle, and we'll go over that in [[v8/Handles]] //and [[v8/Persistent Handles]] Persistent<Context> context = Context::New(); //Create a V8 string containing our source script. It just concatenates //two words with JavaScript's + operator. See [[v8/Values#Strings]] Handle<String> source = String::New("'Hello' + ', World'"); //Compile it. The big deal about V8 is that it compiles JavaScript into //machine code. Well, we need to tell it to do so. See [[v8/Scripts]] Handle<Script> script = Script::Compile(source); //run the script, and get the value, which should equal "Hello, World" Handle<Value> result = script->Run(); //dispose of the context. We don't need it anymore. We ran our script. context.Dispose(); //Convert the result to an ASCII string and print it. Again [[v8/Values#Strings]] String::AsciiValue ascii(result); //write to cout std::cout << "JavaScript says: " << *ascii << "\n"; //and return, now that we have finished. return 0; }
See: