Storing handles to objects in a hashmap or set in Google's V8 engine

China☆狼群 提交于 2019-12-04 13:04:14

This is correct that you can't safely store Local<T> handle, because when it gets out of scope, your function object may become available to garbage collection. What you need is a persistent handle. You can construct it out of local like:

v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(args[0]);
v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function>> value(isolate, cb);

Note CopyablePersistentTraits which allows handle copying. There is also NonCopyablePersistentTraits if you would like to prevent that.

Now you can put it in a vector:

std::vector<v8::Persistent<v8::Function, v8::CopyablePersistentTraits<v8::Function>>> v;
v.push_back(value);

Convert back to local:

v8::Local<v8::Function> local = v8::Local<v8::Function>::New(isolate, value);

For std::set you also need to provide comparison function for elements. It also might be a good idea to wrap v8::Persistent<T> into your own class like PersistentWrapper<T> (this is what I am doing in my project) to get the desired behavior.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!