Can't access V8 Context in “callback” function

我的梦境 提交于 2019-12-13 00:15:16

问题


I am writing a NodeJS addon where I use a C library that lets you register a callback at certain events. When the callback is fired I want to call a NodeJS callback function. The problem is that in my C callback function I get a segmentation fault when trying to do anything V8 related, like creating a HandleScope.

In test.js:

...

myaddon.register(function(data) {
  console.log("data: " + JSON.stringify(data));
});

...

In test.c:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <node.h>
#include <v8.h>

using namespace v8;

void WINAPI myEvent(int num, void * context) {
  HandleScope scope; // Segmentation fault here!

  Local<Function> * cb = (Local<Function>*)(context);

  Local<Object> obj = Object::New();
  obj->Set(String::NewSymbol("id"), Number::New(num));

  const int argc = 1;
  Local<Value> argv[argc] = { obj };
  (*cb)->Call(Context::GetCurrent()->Global(), argc, argv);

  sleep(1);
}

Handle<Value> RegisterEvent(const Arguments& args) {
    HandleScope scope;

    Local<Function> cb = Local<Function>::Cast(args[0]);

    int callbackId  = registerEvent((Event)&myEvent, &cb );
    printf("callback id: %i\n", callbackId);

    init();

    return scope.Close(Integer::New(callbackId));
}

void init(Handle<Object> exports) {
  exports->Set(String::NewSymbol("register"),
      FunctionTemplate::New(RegisterEvent)->GetFunction());
}

NODE_MODULE(test, init)

EDIT: Updated with real code.

EDIT: I just changed the title of this issue since the problem is probably that my callback function can't access the V8 Context. Since I get a segmentation fault when creating HandleScope instance I can't see what else it might be. In addition to this question I AM trying to find the answer in the V8 documentation, but it is huge and I don't have that much time to test and investigate.


回答1:


Your handler function myEvent() must be called in V8 thread. If not, you have to post the event notification into the V8 thread:

https://stackoverflow.com/a/15701160/1355844

https://stackoverflow.com/a/22946062/1355844




回答2:


It appears that you might have forgotten to create a HandleScope for your variable. This should work for you.

void callbackFunc() {
  HandleScope scope;
  Local<Object> obj = Object::New();
}


来源:https://stackoverflow.com/questions/28045047/cant-access-v8-context-in-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!