I'm trying to perform a callback in C++ (where C++ is running as part of a node.js program). The callback is to a 3rd party library, where it will call the callback when it has data to pass.
The problem I appear to be having is with variable types:
static void sensorEventCallback(const char *protocol, const char *model,
int id, int dataType, const char *value, int timestamp,
int callbackId, void *context)
{
//process the data here
}
Handle<Value> sensorEvents( const Arguments& args ) {
HandleScope scope;
...
callbackId = tdRegisterSensorEvent(
reinterpret_cast<TDSensorEvent>(&telldus_v8::sensorEventCallback),
Context::GetCurrent()->Global());
}
The error I'm getting:
error: cannot convert ‘v8::Local<v8::Object>’ to ‘void*’ for argument ‘2’ to ‘int tdRegisterSensorEvent(void ()(const char, const char*, int, int, const char*, int, int, void*), void*)’
It appears to be struggling with argument 2 which is the context. Any thoughts on how I can convert the V8 object to one that tdRegisterSensorEvent will accept?
Snooping a bit, that GetCurrent
appears to be defined in the V8 header to return a Local<Context>
:
v8.h on GitHub, location of GetCurrent() in the Context object definition
This Local<T>
is a template for a "lightweight, stack allocated handle", derived from a base class Handle<T>
:
v8.h on GitHub, definition of Local
v8.h on GitHub, definition of Handle
So seems you've got a Context pointer whose lifetime is being managed by something called a HandleScope
. If you pull the context pointer out and save it to use in a callback later, it may or may not still exist at the time the call is made.
If you know all the callbacks will happen before it's freed by the handle scope, you can try getting the pointer out using the dereference operator overload and passing it:
v8.h on GitHub, T* Handle::operator*()
But you may not have this guarantee.
As n.m. says I would guess the address of the context object should be passed. You can then cast that back in your callback
void telldus_v8::sensorEventCallback(const char *protocol, const char *model,
int id, int dataType, const char *value, int timestamp,
int callbackId, void *context)
{
v8::Local<v8::Object>* ctx_ptr = static_cast<v8::Local<v8::Object>*>(context);
//process the data here
}
v8::Local<v8::Object> ctx = Context::GetCurrent()->Global();
callbackId = tdRegisterSensorEvent(
reinterpret_cast<TDSensorEvent>(&telldus_v8::sensorEventCallback),
&ctx);