我知道这个问题很旧,但我找到的所有答案都不起作用并且已经过时。
但这是我的代码:
void Destroyed(const v8::WeakCallbackData<v8::Object, int>& info)
{
std::cout << "d: " << *info.GetParameter() << std::endl;
}
std::vector<v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>> persistent;
int i = 0;
void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>> per;
per = v8::Persistent<v8::Object>(v8::Isolate::GetCurrent(), info.This());
per.SetWeak<int>(new int(i), Destroyed);
persistent.push_back(per);
++i;
while(!v8::V8::IdleNotification()) {}
}
void TestV8()
{
v8::Isolate* isolate = v8::Isolate::New();
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope contextScope(context);
v8::Local<v8::FunctionTemplate> temp = v8::FunctionTemplate::New(isolate, Constructor);
context->Global()->Set(v8::String::NewFromUtf8(isolate, "Object"), temp->GetFunction());
v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "while(true) {new Object();}");
v8::Local<v8::Script> script = v8::Script::Compile(source);
v8::Local<v8::Value> result = script->Run();
std::cout << *v8::String::Utf8Value(result) << std::endl;
}
如果我不将持久性添加到向量中,内存不会增加。
但 Destroyed 永远不会被调用,我似乎无法弄清楚出了什么问题,请帮忙:)
我解决了,下面是工作代码。显然,持久复制构造函数没有将其复制到弱引用,因此将其转换为指针来解决它。
std::vector<v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>*> persistent;
int i = 0;
void Destroyed(const v8::WeakCallbackData<v8::Object, int>& info)
{
std::cout << "d: " << *info.GetParameter() << std::endl;
persistent[*info.GetParameter()]->Reset();
}
void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>* per = new v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>(v8::Isolate::GetCurrent(), info.This());
per->SetWeak<int>(new int(i), Destroyed);
persistent.push_back(per);
++i;
while(!v8::V8::IdleNotification()) {}
}
void TestV8()
{
v8::Isolate* isolate = v8::Isolate::New();
v8::Isolate::Scope isolateScope(isolate);
v8::HandleScope scope(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate);
v8::Context::Scope contextScope(context);
v8::Local<v8::FunctionTemplate> temp = v8::FunctionTemplate::New(isolate, Constructor);
context->Global()->Set(v8::String::NewFromUtf8(isolate, "Object"), temp->GetFunction());
v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, "while(true) {new Object();}");
v8::Local<v8::Script> script = v8::Script::Compile(source);
v8::Local<v8::Value> result = script->Run();
std::cout << *v8::String::Utf8Value(result) << std::endl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)