如何将std :: function绑定到JavaScript V8?

时间:2013-03-31 16:32:05

标签: javascript c++ binding v8 std-function

我刚开始使用JavaScript V8并编译了Embedder's Guide的基本示例。现在我想将C ++函数绑定到JavaScript上下文。

现在我只有一个或多或少的空白类,以后应该处理绑定。

class Manager
{
public:
    Manager()
    {
        context = Context::New();
    }
    void Bind(string Name, function<Handle<Value>(const Arguments&)> Function)
    {
        // bind the function to the given context
    }
private:
    Persistent<Context> context;
};

如何将std::function对象绑定到JavaScript V8上下文?

2 个答案:

答案 0 :(得分:3)

我在引擎中使用的是一种相当复杂的方法,但是我想出的第一个方法。 (遗憾的是,我从V8转到LLVM,以至于我没有对此进行优化。)

void ExposeFunctions(v8::Handle<v8::ObjectTemplate> engine) {
    /* ... */
    engine->Set(v8::String::New("Exit"), v8::FunctionTemplate::New(NativeExit));
    engine->Set(v8::String::New("Log"), v8::FunctionTemplate::New(NativeLog));
    /* ... */
}

int SpawnEngine() {
    v8::Locker locker;
    v8::HandleScope handleScope;
    v8::TryCatch exceptionManager;
    v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
    ExposeFunctions(global);
    v8::Persistent<v8::Context> context = v8::Context::New(nullptr, global);
    v8::Context::Scope scope(context);
    /* ... */
    context.Dispose();
    return 0;
}

这应该至少为您提供一个可能的解决方案,将本机函数绑定到解释器,您可以根据需要进行重新设计。

考虑到你使用函数对象的问题,我可以尝试(只是在这里猜测)直接传递它,就像我对命名函数所做的那样,或者将它嵌套在传递给v8::FunctionTemplate::New的lambda表达式中。但是自从我使用它以来已经有一段时间了。

答案 1 :(得分:0)

InvocationCallback函数请求的参数类型Set是一个简单的typedef。

typedef Handle<Value> (*InvocationCallback)(Arguments const &);

因此我必须将std::function转换为原始函数指针。

void Register(string Name, function<Handle<Value>(Arguments const &)> Function)
{
    InvocationCallback* function = Function.target<InvocationCallback>();
    globals->Set(String::New(Name.c_str()), FunctionTemplate::New(*function));
}