使用Google的v8 C ++库,我尝试在堆上创建一个v8 :: UniquePersistent实例,该实例包含一个指向C ++中分配的内存的内部指针,并在Persistent上调用SetWeak()来指定回调,当javascript引擎不再需要该句柄时,将通过释放Persistent中的内部指针引用的内存来进行必要的清理。虽然Persistent的创建似乎有效,但我发现我的回调函数永远不会被调用。
我完全被这里难住了。我可能做错了什么想法?
答案 0 :(得分:1)
仅在对象被垃圾回收时才会调用回调。试试这个例子:
void callback(v8::WeakCallbackData<v8::Object, int> data)
{
Local<Object> val = data.GetValue();
int* ptr = retinterpret_cast<int*>(val->GetAlignedPointerFromINternalField(0));
delete ptr;
fprintf(stdout, "Deleted internal object!\n");
}
void main()
{
using namespace v8;
// Enable garbage collection
const char* flags = "--expose_gc";
v8::V8::SetFlagsFromStrings(flags, strlen(flags));
Isolate isolate = Isolate::New();
isolate->Enter();
HandleScope scope(isolate);
Eternal<v8::Context> context;
Local<ObjectTemplate> ctx_template ObjectTemplate::New(isolate);
context.Set(isolate, Context::New(isolate, nullptr, ctx_template);
Local<ObjectTemplate> obj_template = ObjectTemplate::New(isolate);
obj_template->SetInternalFieldCount(1);
Local<Object> obj = Local<Object>(isolate, obj_template->NewInstance());
obj->SetAlignedPointerInInternalField(0, new int);
UniquePersistent<Object> persistent(isolate, obj);
persistent->SetWeak(nullptr, callback);
//...do something with persistent
persistent.Reset();
isolate->RequestGarbageCollectionForTesting(v8::Isolate::kFullGarbageCollection);
// You should see output from the callback
// i need to add more words to pass edit word num check...
}