From: Lyle Johnson Date: 2004-02-09T23:14:59+09:00 Subject: Re: Swig: Extra objects being created Phil Tomson wrote: > I'm finding that accessor methods on a wrapped C++ class end up creating > extra objects on the Ruby side. Here's an example to illustrate: > So after calling the accessor methods 'start_node' and 'end_node' the > number of Point objects is 4 instead of 2. I think this is being caused > by SWIG_NewPointerObj. Maybe there's no way around it. I would have > expected that I would get a reference to an already existing Point object > instead of a new Point object being created. No, you are correct that every time the accessor (or any other method that returns a pointer to some object) is called, you'll get a new Ruby instance that wraps that C++ object. > Is there any way to do this so that no new Point objects are created when > calling Edge#end_node, Edge#start_node? Since my script calls these > methods a lot, lots of extra Point objects get created. I have a workaround for this in FXRuby, but it is a little complicated. Generally speaking, I maintain a little hash table that maps the C++ pointers to the corresponding Ruby objects. When it's time to return a Ruby object from one of these accessors, I first check that hash table to see if there's already a "live" Ruby instance corresponding to the underlying C++ object and, if so, return that Ruby instance. Otherwise, I call SWIG_NewPointerObj() as usual and store this new association in the hash. It might be possible to extend SWIG to automate this process, I'm not sure. We'd have to think about the implications for garbage collection as well; for example, if the Ruby object gets garbage-collected, we need to be sure to remove it from the hash table since it's no longer "alive".