2016-11-29 75 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

这真的有帮助,特别是笔记!谢谢! –