0

当我尝试使持久句柄变弱时,为什么不调用 Wea​​kReferenceCallback?请参阅以下示例:

void myWeakReferenceCallback(v8::Persistent<v8::Value> theValue, void *theParameter)
{
    fprintf(stdout, "myWeakReferenceCallback");
}

void testWeakReferenceCallback()
{
    v8::Persistent<v8::Value> persistent_value;
    {
        v8::Persistent<v8::Context> context = v8::Context::New();
        v8::Context::Scope context_scope(context);
        v8::HandleScope handle_scope;
        v8::Local<v8::Value> local_value = v8::NumberObject::New(5.0);
        persistent_value = v8::Persistent<v8::Value>::New(local_value);
        persistent_value.MakeWeak(NULL, myWeakReferenceCallback);
        context.Dispose();
    }
    persistent_value.Dispose();
}
4

1 回答 1

1

我认为有两个问题:

  1. 在 V8 有机会调用回调之前,您正在处理弱句柄。您需要在回调中处理
  2. V8 在执行 GC 之前不会调用弱句柄回调。

试试这个:

void myWeakReferenceCallback(v8::Persistent<v8::Value> theValue, void *theParameter)
{
    fprintf(stdout, "myWeakReferenceCallback");
    theValue.Dispose();
}

void testWeakReferenceCallback()
{
    v8::Persistent<v8::Value> persistent_value;
    {
        v8::Persistent<v8::Context> context = v8::Context::New();
        v8::Context::Scope context_scope(context);
        v8::HandleScope handle_scope;
        v8::Local<v8::Value> local_value = v8::NumberObject::New(5.0);
        persistent_value = v8::Persistent<v8::Value>::New(local_value);
        persistent_value.MakeWeak(NULL, myWeakReferenceCallback);
        context.Dispose();
    }
    //persistent_value.Dispose();
    while (!v8::V8::IdleNotification()); // force GC
}
于 2013-03-13T04:54:40.523 回答