将类实例函数绑定到 v8::FunctionTemplate

Bind class instance function to v8::FunctionTemplate

本文关键字:v8 FunctionTemplate 绑定 实例 函数      更新时间:2023-10-16

我对 C++ 和 v8 一般来说相当陌生,我想构建一个原生节点.js插件,但现在我被困在非常简单的 IMO 上,但我无法弄清楚问题是什么,错误消息

C:PathToProjectFile.cpp(50): error C2664: 'v8::Local<v8::FunctionTemplate> v8::FunctionTemplate::New(v8::Isolate *,v8::FunctionCallback,v8::Local<v8::Value>,v8::Local<v8::Signature>,int,v8::ConstructorBehavior,v8::SideEffectType)': cannot convert argument 2 from 'v8::Local<v8::Value> (__cdecl *)(const v8::FunctionCallbackInfo<v8::Value> &)' to 'v8::FunctionCallback' [C:PathToProjectbuildnode_gui.vcxproj]

没有那么有帮助。

我有以下代码,

v8::Local <v8::Object> Window::GetFunctions() {
    v8::Local <v8::Object> DrawFunctions = v8::Object::New(isolate);

    v8::Local <v8::FunctionTemplate> bgfnc = v8::FunctionTemplate::New(isolate, &Window::BackgroundCB);
    DrawFunctions->Set(v8::String::NewFromUtf8(isolate, "background"), bgfnc);
    return DrawFunctions;
}
void Window::Background(const v8::FunctionCallbackInfo <v8::Value> &args) {
    v8::Isolate *isolate = args.GetIsolate();
    renderer->Background(args[0]->NumberValue(), args[1]->NumberValue(), args[2]->NumberValue());
}
v8::Handle <v8::Value> BackgroundCB(const v8::FunctionCallbackInfo <v8::Value> &args) {
    return ((Window*)v8::External::Cast(*(args.Data())->Value())->Background());
}

我想创建一个包含函数列表的对象,函数的回调将是 Window 类的成员函数。我知道这之前已经在这里被问过,它曾经使用非成员函数工作过,但除此之外就没有了。

谢谢

旁注:我已经广泛寻找适合初学者的 v8 文档,nodesource 的文档没有解释参数的含义,或者很少给出如何使用函数/类的完整示例,如果有人知道一些更好的文档,那就太好了,谢谢。

感谢社区的亲切和及时的帮助,我能够快速轻松地解决这个问题。事实证明,在编写 NodeJS 插件时,使用 NodeJS 自己的 N-API 是个好主意,因为文档更简单、更清晰,最重要的是,存在。