LoginSignup
16

More than 5 years have passed since last update.

v8でHelloWorld

Last updated at Posted at 2013-10-30

node.jsのv0.11を試していたら、ネイティブモジュールが軒並みビルドできなくなっていて、調べて行ったらどうやらv8のAPIが変わったようです。

いくつかネイティブモジュールを対応させてみようと思ったけどv8自体がよくわからなかったのでHello Worldから始めてみることにしました。

とりあえずv8をインストール。

$ brew install v8
$ v8 
V8 version 3.19.18.4 [sample shell]
> 

バージョン3.19.18.4と言うのが入ったようです。

↑のページを参考にファイルからJavaScriptを読み込んで実行するコードを書いてみました。

hello.cpp
#include <v8.h>

using namespace v8;

Handle<String> ReadFile(const char* name) {
        FILE* file = fopen(name, "r");
        if (file == NULL) return Handle<String>();

        fseek(file, 0, SEEK_END);
        int size = ftell(file);
        rewind(file);

        char* chars = new char[size + 1];
        chars[size] = '\0';
        for (int i = 0; i < size;) {
                int read = fread(&chars[i], 1, size - i, file);
                i += read;
        }

        fclose(file);

        Handle<String> result = String::New(chars, size);
        delete[] chars;
        return result;
}

int main(int argc, char* argv[])
{
        Isolate* isolate = Isolate::GetCurrent();
        HandleScope handle_scope;

        Handle<Context> context = Context::New(isolate);
        Persistent<Context> persistent_context(isolate, context);

        Context::Scope context_scope(context);

        if (argc < 2) {
                fprintf(stderr, "script was not specified.\n");
                return 1;
        }

        Handle<String> source = ReadFile(argv[1]);
        Handle<Script> script = Script::Compile(source);

        Handle<Value> result = script->Run();

        persistent_context.Dispose();

        String::AsciiValue ascii(result);
        printf("%s\n", *ascii);
        return 0;
}

コンパイル

$ g++ -Iinclude hello.cpp -o hello -lv8_base.x64 -lv8_nosnapshot.x64 -lpthread

JavaScriptでHello Worldを作成

test.js
function join(a, b) {
  return a + b;
}

join("Hello", ", World");

実行

$ ./hello test.js 
Hello, World

ちょっと雰囲気が掴めました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16