From: Luigi Ballabio Date: 2002-04-05T01:30:09+09:00 Subject: Re: Help: Ruby<->C++ callbacks Thanks a lot, Tobias. At 12:11 AM 4/5/02 +0900, Tobias Peters wrote: >Since you want to write a "C++ extension to Ruby", you >should defer all memory management to the ruby interpreter. Ok, now I see that I got rb_gc_mark backwards (and it showed in my answer to Guy Decoux. My apologies, Guy.) I still have a question, though---rb_gc_mark protects the object I'm storing, but how do I unmark it? That is, how do I tell the garbage collector that it can dispose of it when I'm done with the object that stores it? Also, now that I knew what to look for, I noticed that SWIG doesn't pass the "mark" function to Data_Wrap_Struct, only the "free" function... Lyle, are you reading? Can we do something about this? Or should I inject the relevant code by hand, instead of relying upon SWIG_NewPointerObj? >There is no need for this Callback class. Yes, there is. Here is the full picture, as much simplified as possible. I'm not writing a C++ extension from scratch: I'm writing bindings for an existing C++ library. The latter defines an abstract Callback class as class Callback { public: virtual ~Callback(); virtual void doit() = 0; }; which can be subclassed to give the desired behavior. The usual Strategy pattern stuff. Another class takes Callbacks and uses them: class AnotherClass { public: void setCallback(Callback* c) { // store the callback } void doYourStuff() { // among other things, c_->doit(); } }; My aim is to provide the user with the ability to define callbacks from Ruby, which is what he would do in C++ by subclassing Callback. He should be made able to write: irb> foo = AnotherClass.new irb> bar = RubyCallback.new(proc { puts "It's me again" }) irb> foo.setCallback(bar) irb> foo.doYourStuff It's me again AnotherClass does not store Ruby objects: it stores Callback pointers. What I'm trying to do is to define a subclass of Callback whose doit() method proxies a Ruby block which is passed upon construction. Thanks again, Luigi