如何将本地<Function>作为参数传递?
How to pass Local<Function> as parameter?
我正在使用v8为node.js编写一个C++库。我在Windows上,我想从C++代码中调用Win32 API函数EnumWindows
。EnumWindows
以一个回调函数和可选的回调函数参数作为参数。我使用这个C++库的唯一目标是将EnumWindows
公开给javascript领域,并按如下方式使用。。。
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));
}
我的问题是如何将EnumWindows
包装器中的Local<Function
传递给EnumWindowsProc
回调函数?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));
}
另一种选择是收集句柄以便稍后处理:
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));
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数