如何将本地<Function>作为参数传递?

How to pass Local<Function> as parameter?

本文关键字:gt 参数传递 Function lt      更新时间:2023-10-16

我正在使用v8为node.js编写一个C++库。我在Windows上,我想从C++代码中调用Win32 API函数EnumWindowsEnumWindows以一个回调函数和可选的回调函数参数作为参数。我使用这个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));
}