如何传递Local <Function>作为参数?
我正在使用v8为node.js编写一个C ++库。 我在Windows上,我想从我的C ++代码中调用Win32 API函数EnumWindows
。 EnumWindows
接受一个callback函数和可选的callback函数参数作为参数。 我这个C ++库的唯一目标是将EnumWindows
公开到javascript-land,并使用如下…
mymodule.EnumWindows(function (id) { ... });
所以,我的C ++代码看起来像这样…
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { // re-cast the Local<Function> and call it with hWnd return true; } Handle<Value> EnumWindows(const Arguments& args) { HandleScope scope; // store callback function auto callback = Local<Function>::Cast(args[0]); // enum windows auto result = EnumWindows(EnumWindowsProc, callback); return scope.Close(Boolean::New(result == 1)); }
我的问题是如何传递Local<Function
,在我的EnumWindows
包装, EnumWindowsProc
callback函数? EnumWindowsProc
在同一个线程中执行。
你可以传递callback
的地址:
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { Local<Function>& f = *reinterpret_cast<Local<Function>*>(lParam); // use f return true; } Handle<Value> EnumWindows(const Arguments& args) { HandleScope scope; // store callback function auto callback = Local<Function>::Cast(args[0]); // enum windows auto result = EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&callback)); return scope.Close(Boolean::New(result == 1)); }
另一种select是收集手柄以便稍后处理它们:
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) { std::vector<HWND>* p = reinterpret_cast<std::vector<HWND>*>(lParam); p->push_back(hWnd); return true; } Handle<Value> EnumWindows(const Arguments& args) { HandleScope scope; // store callback function auto callback = Local<Function>::Cast(args[0]); // enum windows std::vector<HWND> handles; auto result = EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&handles)); // Do the calls... return scope.Close(Boolean::New(result == 1)); }