2016-11-29 72 views
0

我遇到這個錯誤時,寫一個nodejs c/c + +插件,它發生時,我嘗試存儲一個異步回調持久。沒有匹配函數調用Persistent <Function> ::新(隔離*&,本地<Function>&)

但我在v8.h中發現了聲明:V8_INLINE持久性(Isolate * isolate,Local < S> that)。通話似乎沒有任何問題。

附上我的代碼。先謝謝你!它讓我困惑了幾天。

struct reqData 
{ 
    int result; 
    int a; 
    int b; 
    char name[128]; 
    Persistent<Function> callback; 
}; 

static Handle<Value> test(const FunctionCallbackInfo<Value>& args) 
{ 
    Isolate *isolate = Isolate::GetCurrent(); 
    HandleScope scope(isolate); 
    if (args.Length() < 3 || !args[0]->IsNumber() || !args[1]->IsNumber()) 
    { 
     return (*isolate).ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Bad argument"))); 
    } 

    ssize_t int1 (args[0]->Int32Value()); 
    ssize_t int2 (args[1]->Int32Value()); 
    char nameBuffer[128] = {0}; 
    args[2]->ToString()->WriteOneByte(nameBuffer); 

    if (args[3]->IsFunction()) 
    { 
     Local<Function> callback = Local<Function>::Cast(args[3]); 

     reqData* request = new reqData; 
     request->callback = Persistent<Function>::New(isolate,callback); 



     request->a = int1; 
     request->b = int2; 
     strcpy(request->name, nameBuffer); 

     uv_work_t* req = new uv_work_t(); 
     req->data = request; 

     uv_queue_work(uv_default_loop(), req, workerFunc, afterWorkFunc); 
    } 
    else 
    { 
     return (*isolate).ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Callback missing"))); 
    } 

    return Undefined(isolate); 
} 

extern "C" 
{ 
    // equal to js 
    // 
    // exports.test = function Test(){}; 
    // 
    static void init(Local<Object> exports) 
    { 
     //target->Set(String::NewSymbol("asyncAddon"), FunctionTemplate::New(test)->GetFunction()); 
     NODE_SET_METHOD(exports, "asyncAddon", test); 
    } 
} 

NODE_MODULE(asyncAddon, init) 
+0

您所針對的節點的版本是? – mscdex

+0

@mscdex Node.js v6.2.0。 –

回答

0

眼前的問題是,你不這樣做Persistent<..>::New(),你只是.Reset()與價值要在Persistent存儲。例如:

request->callback.Reset(isolate, callback); 

其他注意事項:

  • 你不需要在test()一個HandleScope因爲函數已經被直接從JavaScript調用,因此已經有一個活躍的範圍。當您在主線程上使用V8 API時,只需要一個HandleScope,它來自libuv線程池或其他不是直接來自JS land的其他位置。

  • 你應該真的考慮使用nan。它有助於平滑跨V8版本的差異,並允許您不必擔心細節如孤立和其他事情。

  • 如果您還不熟悉它們,請在線獲取V8 API文檔here

+0

這真的有幫助,特別是筆記!謝謝! –