1

我正在尝试在 C++ 中执行回调(其中 C++ 作为 node.js 程序的一部分运行)。回调是到第 3 方库,当它有数据要传递时,它将调用回调。

我似乎遇到的问题是变量类型:

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

我得到的错误:

错误:无法将 'v8::Local<v8::Object>' 转换为 'void*' 参数 '2' 到 'int tdRegisterSensorEvent(void ( )(const char , const char*, int, int, const char*, int, int, void*), void*)'</p>

它似乎在与作为上下文的论点 2 作斗争。关于如何将 V8 对象转换为 tdRegisterSensorEvent 将接受的对象的任何想法?

4

2 回答 2

4

稍微窥探一下,这GetCurrent似乎是在 V8 标头中定义以返回 a Local<Context>

GitHub 上的 v8.h,上下文对象定义中 GetCurrent() 的位置

这是从基类派生的“轻量级堆栈分配句柄”Local<T>的模板:Handle<T>

GitHub上的v8.h,Local的定义

GitHub上的v8.h,Handle的定义

所以看起来你有一个 Context 指针,它的生命周期由一个叫做HandleScope. 如果您将上下文指针拉出并保存以供稍后在回调中使用,则在进行调用时它可能仍然存在,也可能不存在。

如果您知道所有回调将在句柄范围释放之前发生,您可以尝试使用取消引用运算符重载获取指针并传递它:

GitHub 上的 v8.h,T* Handle::operator*()

但是你可能没有这个保证。

于 2012-11-21T08:03:27.843 回答
1

正如 nm 所说,我猜应该传递上下文对象的地址。然后你可以在你的回调中将其转换回

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);
于 2012-11-21T08:02:38.510 回答