尝试在回调中获取Isolate时V8中的C ++ null引用

时间:2015-06-24 19:36:09

标签: c++ node.js v8

我正在试图弄清楚我的代码中哪些不起作用。我有一个第三方库-dll,它有一个方法,我在方法“RegisterSensorEvent”中调用。我们的想法是第三方方法采用回调方法和指向上下文的void指针。我将JS回调作为上下文传递,然后尝试在“SensorEventCallback”中调用它。我试过调试,我只能到:

Isolate* isolate = Isolate::GetCurrent(); (first line in method SensorEventCallback)

然后我得到nullref异常。这里有明显的错误吗?

struct EventContext {
        v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function>> callback;
    };

    void SensorEventCallback(const char *protocol, const char *model, int sensorId, int dataType, const char *value, int ts, int callbackId, void *callbackVoid) {
        Isolate* isolate = Isolate::GetCurrent();
        EventContext *ctx = static_cast<EventContext *>(callbackVoid);
        v8::Local<v8::Function> function = v8::Local<v8::Function>::New(isolate, ((v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function>>)ctx->callback));
        const unsigned argc = 1;
        Local<Value> argv[argc] = { v8::Number::New(isolate, sensorId) };
        function->Call(isolate->GetCurrentContext()->Global(), argc, argv);
    }

    void RegisterSensorEvent(const v8::FunctionCallbackInfo<v8::Value>& args){
        Isolate* isolate = Isolate::GetCurrent();
        v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(args[0]);
        v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function>> value(isolate, cb);

        EventContext *ctx = new EventContext();
        ctx->callback = value;

        Local<Number> num = Number::New(isolate, tdRegisterSensorEvent((TDSensorEvent)&SensorEventCallback, ctx));
        args.GetReturnValue().Set(num);
    }

JS代码:

var registeredEventId = someModule.AddSensorEventListener(function (args) {
    console.log("This is value from callback: " + args);
});

编辑:

所以我改变了方法(删除了所有的V8东西):

void SensorEventCallback(const char *protocol, const char *model, int sensorId, int dataType, const char *value, int ts, int callbackId, void *callbackVoid) {
        SensorEventBaton *baton = new SensorEventBaton();
        baton->ctx = callbackVoid;

        uv_async_t* asyncHandle = new uv_async_t;
        asyncHandle->data = baton;

        uv_async_init(uv_default_loop(), asyncHandle, (uv_async_cb)SensorEventCallbackAfter);
    }

struct SensorEventBaton {
        void *ctx;
    };

但我仍然会遇到错误。这次我甚至没有进入SensorEventCallbackAfter方法。我得到的错误如下:

node.exe:0xC0000005:访问冲突写入位置0x6CB55EF8。

0 个答案:

没有答案