我正在尝试在 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());
}
我得到的错误:
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*)’
它似乎在与作为上下文的参数 2 作斗争。关于如何将 V8 对象转换为 tdRegisterSensorEvent 将接受的对象,有什么想法吗?
最佳答案
稍微窥探一下,GetCurrent
似乎在 V8 header 中定义为返回 Local<Context>
:
v8.h on GitHub, location of GetCurrent() in the Context object definition
这Local<T>
是“轻量级堆栈分配句柄” 的模板,派生自基类Handle<T>
:
v8.h on GitHub, definition of Local
v8.h on GitHub, definition of Handle
看来你有一个 Context 指针,它的生命周期由一个叫做 HandleScope
的东西管理。 .如果您拉出上下文指针并将其保存以供稍后在回调中使用,则在进行调用时它可能仍然存在,也可能不存在。
如果您知道所有回调都会在它被句柄作用域释放之前发生,您可以尝试使用取消引用运算符重载获取指针并传递它:
v8.h on GitHub, T* Handle::operator*()
但你可能没有这个保证。
关于C++ V8 对象上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13488402/