开发者

Possible to create C++ objects on the V8 garbge collected heap?

开发者 https://www.devze.com 2023-03-04 20:01 出处:网络
I have the V8 engine embedded in a C++ 开发者_C百科application. I wish to take advantage of the built in garbage collector (in particularly the compacting feature) in V8 but wish to store C++ objects

I have the V8 engine embedded in a C++ 开发者_C百科application.

I wish to take advantage of the built in garbage collector (in particularly the compacting feature) in V8 but wish to store C++ objects instead.

I don't mind needing to call the collector manually to dispose of the object, as long as the memory can be reclaimed.


Interesting thought. I have not used V8 but I have written C++ garbage collectors. I think the answer will actually depend on the algorithm V8 uses for garbage collection. A mark-and-sweep collector, which treats memory as completely flat, will work for any program but its terribly slow. Most collectors do more language specific optimizations and use actual object sizes and compiler hints to speed things up, this wont work with C++.

I should mention that generational collectors can also work as long as they don;t use compiler hints and treat memory naively.

The GC i wrote used my own version of smart pointers and it worked very well for my specific workload.


It's explained here: http://code.google.com/apis/v8/embed.html#handles

For more info search for v8 weak handles.


My guess that the answer is no, because V8 doesn't know an internal structure of C++ objects.

You need the GC to be able to scan C++ objects. If you have a code like

struct A {
    v8::Handle<A> a;
    v8::Handle<A> b;
};

v8::Handle<A> rootObject;

you expect that GC will scan rootObject, check that it has links to a and b and mark a and b feasible, but rootObject is a black box for V8 and it doesn't know that it owns references to a and b. I think that adding the ability to scan C++ objects is as hard as writing a GC from scratch.


Yes, but not without some work. V8 provides PersistentBase::SetWeak to make a weak handle, which allows you to define a callback that you could use to delete your native object on garbage collection. However, unfortunately V8 does not guarantee that the callback will be called. So, you need to keep track of the native objects created, and if they haven't had the callback invoked in the meantime, delete them yourself after shutting down the isolate with v8::Isolate::Dispose.

0

精彩评论

暂无评论...
验证码 换一张
取 消