我刚开始使用 JavaScript V8并从 Embedder's Guide 编译了一个基本示例.现在我想将 C++ 函数绑定(bind)到 JavaScript 上下文。
现在我只有一个或多或少的空白类,稍后应该处理绑定(bind)。
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
对象绑定(bind)到 JavaScript V8 上下文?
最佳答案
我在我的引擎中使用的是一种相当复杂的方法,但这是我首先想到的。 (遗憾的是,我从 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;
}
这应该至少为您提供了一个将 native 函数绑定(bind)到解释器的可能解决方案,您可以根据需要对其进行修改。
考虑到您使用函数对象的问题,可以尝试(只是猜测)像我对命名函数所做的那样直接传递它,或者将它嵌套在传递给 v8::FunctionTemplate::New
的 lambda 表达式中.但是我已经有一段时间没有使用它了。
关于javascript - 如何将 std::function 绑定(bind)到 JavaScript V8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15731699/