Re: Typecast error



On Tuesday 13 March 2001 22:33, Havoc Pennington wrote:
> Dwight Tuinstra <tuinstra northnet org> writes:
> > It wants a pointer to something, so, we give it one:
> >
> >   gint dummy_int = 1;
> >   gtk_signal_connect( GTK_OBJECT( robot_name[1] ), "clicked",
> >           GTK_SIGNAL_FUNC( display_info ), &dummy_int );
>
> No! Once you're in the callback, dummy_int will no longer exist;
> you'll have a pointer to random memory.
> 
> The correct, portable, no-warnings way to write this code is:
>
> void
> display_info (GtkWidget *widget, gpointer data)
> {
>   gint i;
>
>   i = GPOINTER_TO_INT (data);
>
>   cout << i << endl;
> }
>
> ....
>   gtk_signal_connect (GTK_OBJECT (robot_name[1]), "clicked",
>                       GTK_SIGNAL_FUNC (display_info ),
>                       GINT_TO_POINTER (42));

You're right about a pointer to random data.  But casting
pointers to ints, and vice-versa, has always seemed to me
a horrible abuse of the type system (I guess I've been 
overly influenced by contact with the ML language's Vorlon-
strict typing).  It would seem that the above code assumes 
that sizeof(gpointer) == sizeof(gint), to prevent data loss;
is this guaranteed in gtk?

Would simply declaring dummy_int static or external solve
the problem?  I'd be much more comfortable with that, even
though it does introduce an extraneous variable.

While we're on this topic, what is the right way to declare
and pass an array of GtkObjects (in my case, GtkAdjustments)
in a signal_connect/callback situation?  (I have an adjustment
whose value depends on the value of several other adjustments).

--Dwight Tuinstra
    tuinstra northnet org




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]