C++ null reference in V8 when trying to get Isolate in callback

1k views Asked by At

I'm trying to figure out what in my code that does not work. I have a third party library-dll that has a method that i call in a method "RegisterSensorEvent". The idea is that the 3rd party method takes a callback method and a void pointer to a context. I pass a JS callback as context and then try to call it in "SensorEventCallback". I've tried to debug and i only get to:

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

And there i get nullref exception. Are there any obvious mistakes here?

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 Code:

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

EDIT:

So i changed method to this (removed all V8-stuff):

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;
    };

But i still get errors. This time i don't even get to the SensorEventCallbackAfter-method. I get error like:

node.exe: 0xC0000005: Access violation writing location 0x6CB55EF8.

0

There are 0 answers