1

v8を使用してC++でnodejsモジュールを開発しようとしています。

ここにソースコードがあります。

#include <node.h>

using namespace v8;

void TestContext1(const FunctionCallbackInfo<Value>& args) {

    Isolate* isolate = Isolate::New();
    {
        Isolate::Scope isolate_scope(isolate);
        V8::Initialize();
        Locker lock(isolate);

        HandleScope handle_scope(isolate);

        Local<Context> context = Context::New(isolate);
        Context::Scope context_scope(context);


        Handle<String> strExpr = Handle<String>::Cast(args[0]);
        Handle<Script> script;
        Handle<Value> res;

        TryCatch tryCatch;
        script = Script::Compile(strExpr);
        res = script->Run();

        if (tryCatch.HasCaught()) {
            res = tryCatch.Message()->Get();
        }

        args.GetReturnValue().Set(res);
    }
    isolate->Dispose();

}


void TestContext2(const FunctionCallbackInfo<Value>& args) {

    Isolate *isolate = args.GetIsolate();
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);
    Local<Context> context = Context::New(isolate);
    Context::Scope context_scope(context);

    Handle<String> strExpr = Handle<String>::Cast(args[0]);
    Handle<Script> script;
    Handle<Value> res;

    TryCatch tryCatch;
    script = Script::Compile(strExpr);
    res = script->Run();

    if (tryCatch.HasCaught()) {
        res = tryCatch.Message()->Get();
    }

    args.GetReturnValue().Set(res);
}

void Init(Handle<Object> exports, Handle<Object> module) {
    NODE_SET_METHOD(exports, "TestContext1", TestContext1);
    NODE_SET_METHOD(exports, "TestContext2", TestContext2);
}

NODE_MODULE(addon, Init)

そして、js コードでテストします。

var addon = require('addon.node')
var i = 0;
setInterval(function () {
    msg = addon.TestContext1("process.exit()"); // or msg = addon.TestContext2("process.exit()");
    console.log(msg, i++, process.memoryUsage().heapUsed/1024/1024);
}, 2);

すべての関数にはさまざまな問題があります。

TestContext1は正常に動作しますが、グローバル コンテキストにアクセスしてプロセスをシャットダウンします。

TestContext2はグローバル コンテキストにアクセスできませんが、メモリ リークが発生します。

私が必要とするすべて - メモリリークなしで分離されたコンテキストで js スクリプトを実行します。

vm.runInNewContext() に同じメモリ リークがあるため、ノード vm は機能しません。

誰かアイデアはありますか?

4

0 に答える 0