2014-03-06 47 views
1

我是V8嵌入的新手,剛剛開始用V8庫替換當前的腳本語言。但是我遇到了一些非常奇怪的問題(至少對我來說)。它有點像我是唯一一個在做我正在做的事情,我覺得我在做一些愚蠢的事情。V8 C++嵌入問題

我做了一個包裝類來包裝V8引擎的功能和我的包裝在建造時,構建引擎(儘量忽略低劣的變量名或愚蠢的樣式):

engine.h:

namespace JSEngine { 

class Engine 
{ 
    public: 
     Engine(); 
     virtual ~Engine(); 
     v8::Isolate* isolate; 
     v8::Handle<v8::Context> context; 
}; 
} 

engine.cpp(其中包括engine.h):

JSEngine::Engine::Engine() 
{ 
    v8::Locker locker(); 
    V8::Initialize(); 

    this->isolate = Isolate::GetCurrent(); 
    HandleScope scope(this->isolate); 

    this->context = Context::New(this->isolate); 
} 

該代碼是罰款和花花公子,但是一旦我試試這個:

Server::jsEngine = new JSEngine::Engine(); 
HandleScope scope(Server::jsEngine->isolate); 
Context::Scope context_scope(Server::jsEngine->context); 

Handle<String> source = String::NewFromUtf8(Server::jsEngine->isolate, "'Hello' + ', World!'"); 
Handle<Script> script = Script::Compile(source); 
Handle<Value> result = script->Run(); 

String::Utf8Value utf8(result); 
printf("%s\n", *utf8); 

我得到這一行段故障:Context::Scope context_scope(Server::jsEngine->context);

我不知道我做錯了,或者如果這種做法甚至是最好的做法。你能幫我解決分段故障錯誤嗎?

回答

1

您的上下文成員變量是本地句柄,在本地範圍內創建,並且只要您的引擎構造函數完成因爲範圍被刪除而無效。你的上下文需要一個持久的句柄。改變你的引擎聲明使用

v8::Persistent<v8::Context> context; 

,當你實際創建的背景下,使用

this->context.Reset(this->isolate, Context::New(this->isolate)); 

,並在你的析構函數,使用

this->context.Reset();