Created
October 2, 2011 14:18
-
-
Save m-mizutani/1257492 to your computer and use it in GitHub Desktop.
v8 Javascript Engine Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// build) g++ v8_test.cc -o v8_test -lv8 | |
#include <v8.h> | |
#include <string> | |
char * js_src = | |
"function laugh() {" | |
" print ('HAHAHA'); " | |
"}; " | |
"s = append ('echo');" | |
"print (s);" | |
"print ('I am ' + obj_test.name); " | |
"obj_test.func ();"; | |
v8::Handle<v8::Value> PrintArgs (const v8::Arguments &args) { | |
v8::String::AsciiValue str(args[0]); | |
printf ("[Print] '%s'\n", *str); | |
return v8::Undefined (); | |
} | |
v8::Handle<v8::Value> PrintTest (const v8::Arguments &args) { | |
printf ("[Print Test]\n"); | |
return v8::Undefined (); | |
} | |
v8::Handle<v8::Value> AppendExclamation (const v8::Arguments &args) { | |
v8::String::AsciiValue str(args[0]); | |
std::string s (*str); | |
s += "!!!"; | |
return v8::String::New (s.c_str (), s.length()); | |
} | |
int main(int argc, char* argv[]) { | |
v8::HandleScope handle_scope; | |
v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New (); | |
// install a original function to global context | |
global->Set(v8::String::New ("print"), v8::FunctionTemplate::New (PrintArgs)); | |
global->Set(v8::String::New ("append"), v8::FunctionTemplate::New (AppendExclamation)); | |
// install a object to global context | |
v8::Handle<v8::ObjectTemplate> obj = v8::ObjectTemplate::New (); | |
obj->Set ("name", v8::String::New ("DROID")); | |
obj->Set ("func", v8::FunctionTemplate::New (PrintTest)); | |
global->Set ("obj_test", obj); | |
// create a source code and compile | |
v8::Handle<v8::String> source = v8::String::New(js_src); | |
v8::Handle<v8::Primitive> undef = v8::Undefined (); | |
v8::Persistent<v8::Context> context = v8::Context::New(NULL, global); | |
v8::Context::Scope context_scope(context); | |
v8::Handle<v8::Script> script = v8::Script::Compile(source, undef); | |
v8::Handle<v8::Value> result = script->Run(); | |
context.Dispose(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment