V8 JavaScriptエンジンの組み込み
Rev.1を表示中。最新版はこちら。
概要
V8 JavaScriptエンジンの組み込みと関数等の追加を試した。
V8の組み込み
まずは標準入力からJavaScriptソースを読み込んで実行するケース。
https://developers.google.com/v8/get_startedに載っているものとほぼ同じで、ソースを標準入力から取得するように修正しただけ。このソースをベースに試していく。
#include <v8.h>
#include <iostream>
#include <string>
using namespace v8;
static void read_file(std::istream& ifs, std::string &content)
{
content = "";
std::string t;
while (!ifs.eof()) {
getline(std::cin, t);
content += t + "\n";
}
}
int main(int argc, char* argv[])
{
std::string js_str;
read_file(std::cin, js_str);
// Create a stack-allocated handle scope.
HandleScope handle_scope;
// Create a new context.
Persistent<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(js_str.c_str());
// Compile the source code.
Handle<Script> script = Script::Compile(source);
// Run the script to get the result.
Handle<Value> result = script->Run();
// Dispose the persistent context.
context.Dispose();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
Build手順は省略。以下のtest.jsを読み込ませて実行してみると。
test.js
(function()
{
return "test test";
})();
実行結果
# ./a.out < test.js test test
関数のリターン値"test test"が表示される。これで、いろいろ試す準備が整った。
