[Gtk-sharp-list] SubWidget problems

Dan Winship danw@novell.com
Wed, 15 Dec 2004 10:48:21 -0500


On Tue, 2004-12-14 at 19:41 -0600, Sergio Duran wrote:
> I created a Widget (DBMenu) that inherits from Gtk.Menu, it works ok,
> but sometimes it ends up reading an empty instance of itself, I set
> some variables in the ctor, and I end up dealing with an instance with
> those variables unitialized, I found some stuff that said one should
> add a ctor(IntPtr x) but then it instantiates the class when it
> shouldnt be doing it, apparently randomly so get some weird crashes.
> 
> I found some links that said that it is related to gtk and c#'s
> garbage collection.

The issue is that for every Gtk# object, there are actually two
different "objects" created; the underlying C-based GObject, and the
C#/managed object that wraps it.

The problem is that when you add your DBMenu to a C-based container
widget, the container only keeps track of the GObject part, not the
managed part. So if there are no other references to the managed object,
it will get garbage collected, even though the C-based object is still
there.

So then if Gtk# finds a reference to the C-based object later, it needs
to create a new managed wrapper for it. This is what the IntPtr ctor is
for. However, as you've discovered, it's only safe to have an IntPtr
ctor if you can completely reconstruct the wrapper object's state from
the C-based object.

If you can't do that, the easiest thing to do is to make sure that
something somewhere in managed code keeps a reference to the DBMenu
object so that it won't be garbage collected.

The good news is that this problem will be fixed in Gtk# 2.0

-- Dan