From: nobu.nokada@... Date: 2001-12-28T11:38:00+09:00 Subject: [ruby-talk:29506] Re: GC and values in extensions Hi, At Fri, 28 Dec 2001 05:34:13 +0900, Johann Hibschman wrote: > rb_gc_register_address looks promising, but I'm left wondering if > anything bad would happen if I registered a variable which is already > accessible through Ruby, or if I registered the same memory location > twice. When I wrote such codes once, I used a static Array to hold all VALUEs referred by C++ objects. You can use a Hash instead in recent 1.7. class RBObject { VALUE obj; static VALUE initialize(VALUE obj = 0); public: RBObject(VALUE v) : obj(initialize(v)) {} virtual ~Object(); }; #ifdef HAVE_RB_HASH_DELETE # define TABLE_NEW() rb_hash_new() # define TABLE_ADD(obj) rb_hash_aset(objects, (obj), Qfalse) # define TABLE_DEL(obj) rb_hash_delete(objects, (obj)) #else # define TABLE_NEW() rb_ary_new() # define TABLE_ADD(obj) rb_ary_push(objects, (obj)) # define TABLE_DEL(obj) rb_ary_delete(objects, (obj)) #endif static VALUE objects = (ruby_init(), rb_gc_register_address(&objects), TABLE_NEW()); VALUE RBObject::initialize(VALUE obj) { if (!rb_special_const_p(obj)) TABLE_ADD(obj); return obj; } RBObject::~Object() { if (!rb_special_const_p(obj)) TABLE_DEL(obj); obj = 0; } I put complete sample code at http://member.nifty.ne.jp/nokada/archive/libruby++-0.2.0.tar.bz2 > void foo(VALUE r_obj) { > RBObject cpp_obj(r_obj); // Hold a reference to r_obj > <> > return; // Destruction of cpp_obj frees ref. > } In this case, since the caller of foo() can hold r_obj, you don't need to hold reference within foo(). Nobu Nakada