Re: [gtk-list] Passing Multiple Arguments to a Callback
- From: Havoc Pennington <rhpennin midway uchicago edu>
- To: gtk-list redhat com
- Subject: Re: [gtk-list] Passing Multiple Arguments to a Callback
- Date: Mon, 28 Sep 1998 21:49:43 -0500 (CDT)
On Mon, 28 Sep 1998, Jordan Nelson wrote:
>
> Is there a way to pass multiple arguments to a callback?
>
C won't let you have more than one signature for the same function.
Gtk-- allows it. In C you will have to make the args into one arg; for
example,
struct multi_arg_t {
gchar* data1;
gchar* data2;
};
Of course, use the appropriate types and think of better names according
to your application.
> strcpy( arg, "Test Value" );
>
g_strdup is easier BTW.
> gtk_signal_connect( GTK_OBJECT( object ), "clicked",
> GTK_SIGNAL_FUNC( callback ), structure, arg );
>
First off you are going to need a pointer, not an entire struct, as the
callback data.
There is only one data argument; you will have to pack all your data into
one place somehow. Either create a struct, as above, or you can use
gtk_object_set_data to store additional data on either the object emitting
the signal or an object you pass in the data field.
> void callback( char *structure, char *value )
> {
> strcpy( structure->data, value );
> g_print( "%s\n", structure->data );
> g_print( "%s\n", value );
> }
>
This won't compile; you can't call -> on a char*. It will also SEGV
because your function signature is wrong.
For callbacks, you should use the signature shown in the object's class
struct. e.g.,
void (* pressed) (GtkButton *button);
void (* released) (GtkButton *button);
void (* clicked) (GtkButton *button);
void (* enter) (GtkButton *button);
void (* leave) (GtkButton *button);
for GtkButton. There is an implicit "gpointer data" on each signature.
So the clicked signal callback should be:
void clicked_callback(GtkButton* button, gpointer data);
If your data is a struct multi_arg_t*, the callback can be:
{
struct multi_arg_t* mat = (struct multi_arg_t*) data;
g_print("Got data %s\n", mat->data1);
g_print("Got data %s\n", mat->data2);
}
You could also have set_data on the button, then:
{
gchar* str = (gchar*)gtk_object_get_data(GTK_OBJECT(button),"my_key");
g_print("Got data %s\n", str);
}
You can pass as much data as you want by using different keys. But this is
a little less efficient than the struct approach probably.
Be careful with casts. Notice that the callback for "clicked" on a
GtkButton is going to get a GtkButton* and a gpointer. If you give the
function a different signature you're implicitly casting those two args to
something else; and you had better be right or things will break.
Havoc
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]