2012-11-21 52 views
0

我想在C++中執行回調(其中C++作爲node.js程序的一部分運行)。回調是第三方庫,當數據通過時它將調用回調函數。C++ V8對象上下文

我似乎遇到的問題是與變量類型:

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可以接受的想法?

+1

看起來你需要傳遞對象的地址而不是對象本身。 –

+0

@ n.m。不應該主張[貨物崇拜編程](http://en.wikipedia.org/wiki/Cargo_cult_programming)*(特別是當v8.h是公開源代碼時)*。 'Context :: GetCurrent() - > Global()'返回一個'Local '... – HostileFork

+2

@HostileFork:我應該說「一個對象」而不是「對象」,對此我表示歉意。如果一個C函數需​​要一個'void *',你通常會傳遞一個對象的地址。我沒有任何意義。 –

回答

3

Snooping的一點,那GetCurrent出現在V8頭被定義爲返回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

所以看起來你已經有了一個上下文指針,其壽命是由一些管理稱爲HandleScope。如果將上下文指針拉出並將其保存爲稍後使用的回調函數,則在進行調用時該指針可能存在也可能不存在。

如果你之前知道它是由手柄範圍釋放將會發生所有的回調,你可以嘗試,取得指向了使用引用操作符重載和傳遞:

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

但你可能沒有這個保證。

+0

非常棒的信息,謝謝!您比我做的更理解文檔!事實上,回調可能會在事件註冊後的幾個小時內發生 - 我將不得不尋找另一種讓node.js與C++交談並避免處理的方法。 – RichW

+1

這些都不是在文檔中,所以我只是去了並閱讀標題...! – HostileFork

+0

@RichW這就是爲什麼Persistant 是爲 – ShrekOverflow

1

至於中午說我會猜測應該傳遞上下文對象的地址。然後,您可以投,早在你的回調

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); 
+0

我認爲關於開源革命的好處是我們不必猜測*! : -/*(這是一個本地',請參閱[我的答案](http://stackoverflow.com/a/13488780/211160))* – HostileFork