Skip to content

Commit

Permalink
make v8 and ruby weak references cooperate when it comes to who delet…
Browse files Browse the repository at this point in the history
…es the memory.
  • Loading branch information
cowboyd committed May 25, 2011
1 parent a671d6f commit e256cee
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
15 changes: 13 additions & 2 deletions ext/v8/v8_weakref.cpp
Expand Up @@ -4,13 +4,16 @@
using namespace v8;

v8_weakref::v8_weakref(VALUE object) {
this->v8_active = true;
this->rb_active = true;
this->external = Persistent<External>::New(External::New((void *)this));
this->external.MakeWeak(this, v8_weakref_dispose);
this->set(object);
}

void v8_weakref::set(VALUE value) {
this->object_id = rb_obj_id(value);
this->rb_active = true;
VALUE data = Data_Wrap_Struct(rb_cObject, 0, 0, this);
rr_define_finalizer(value,(void*)v8_weakref_finalize, data);
}
Expand All @@ -27,13 +30,21 @@ VALUE v8_weakref_finalize(VALUE object_id, VALUE data) {
v8_weakref* weakref = 0;
Data_Get_Struct(data, struct v8_weakref, weakref);
weakref->object_id = Qnil;
weakref->rb_active = false;
if (!weakref->v8_active) {
delete weakref;
}
return Qnil;
}

void v8_weakref_dispose(Persistent<Value> value, void* weakref) {
void v8_weakref_dispose(Persistent<Value> value, void* data) {
value.Dispose();
value.Clear();
delete (v8_weakref*)weakref;
v8_weakref* weakref = (v8_weakref*)data;
weakref->v8_active = false;
if (!weakref->rb_active) {
delete weakref;
}
}

VALUE v8_weakref_nil(VALUE nil, VALUE exception) {
Expand Down
2 changes: 2 additions & 0 deletions ext/v8/v8_weakref.h
Expand Up @@ -13,6 +13,8 @@ struct v8_weakref {
void release();

VALUE object_id;
bool v8_active;
bool rb_active;
v8::Persistent<v8::External> external;
};

Expand Down

0 comments on commit e256cee

Please sign in to comment.