ちょっと思うところあってv8 javascript engine(http://code.google.com/p/v8/)で遊んでみました。公式のドキュメントがだいぶ少ないのですが、いろんな人が2年くらい前に遊んでいたようなので情報は適度に転がっています。
ソースコード
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; | |
} |
実行結果
とりあえず、関数作ってJavaScript側から呼びだすところまでは完成。C++側でJavaScriptの関数を呼び出すところまでやりたいので、後日もうちょっと調べます。[Print] 'echo!!!' [Print] 'I am DROID' [Print Test]
参考文献
- V8 JavaScript Engine Getting Started http://code.google.com/intl/ja/apis/v8/get_started.html
- Google Chrome の JavaScript エンジン V8 を試す http://d.hatena.ne.jp/amachang/20080903/1220405193
- Embedder's Guide - V8 JavaScript Engine (日本語訳) http://javascript.g.hatena.ne.jp/edvakf/20100407/1270626241
- Using V8 - Google's Chrome JavaScript Virtual Machine http://www.codeproject.com/KB/library/Using_V8_Javascript_VM.aspx