如何在V8中的函数模板中存储对外部指针的引用?

时间:2015-06-25 17:21:33

标签: c++ v8

我正在尝试为V8中的C ++类包装器创建一个模板:

var obj1 = myfunc(1);
var obj2 = myfunc(2);

这应该创建两个JS对象,这些对象是这些C ++对象的包装器:

new MyClass(1, shared);
new MyClass(2, shared);

shared是另一个类的单个实例,在范围内的所有对象之间共享。

这是我到目前为止所得到的:

static void myfuncConstructor(const FunctionCallbackInfo<Value>& args)
{
    Isolate* isolate = args.GetIsolate();
    HandleScope scope(isolate);

    uint64_t var1;

    if (args[0].IsEmpty() || !args[0]->IsNumber())
        return;

    var1 = args[0]->NumberValue();

    AnotherClass* shared = IDontKnowHowToGetShared();

    //                     ^ How do I do this?

    MyClass* obj = new MyClass(var1, AnotherClass* shared);

    //                                             ^ this has to be shared between all instances

    args.This()->SetInternalField(0, External::New(isolate, obj));
}


Local<FunctionTemplate> myfuncTemplate(Isolate* isolate, AnotherClass* shared)
{
    Local<FunctionTemplate> t = FunctionTemplate::New(isolate, myfuncConstructor);
    Local<ObjectTemplate> instance = t->InstanceTemplate();
    instance->SetInternalFieldCount(1);
    IDontKnowHowToSetShared(shared);

    //        ^ How do I do this?

    return t;
}

GlobalClass::Compile (const char* code, AnotherClass* shared)
{
    Isolate::Scope isolate_scope(pimpl_->isolate);
    HandleScope handle_scope(pimpl_->isolate);
    Handle<ObjectTemplate> global = ObjectTemplate::New(pimpl_->isolate);
    global->Set(String::NewFromUtf8(pimpl_->isolate, "myfunc"), myfuncTemplate(pimpl_->isolate, shared));
    ...
}

0 个答案:

没有答案