0

Welp, thats a kind of a pointerception.
So.
Im using gtk+
In gtk I define buttons like this:

GtkWidget *button1, *button2;

so I need a function do do something with this. So I make a struct that will hold a pointer to it
Here it is:

typedef struct userdata{
    GtkWidget *button1, *button2;
}userdata;

I point pointers from struct to pointers from main:

userdata data;
data.button1 = button1;
data.button2 = button2;

Then I use this struct with gtk event:

g_signal_connect(G_OBJECT(window), "configure-event", G_CALLBACK(resetbuttonsize), &data);

And here comes the problem. I want to do something with these variables I just sent to function, for example resize them so I do something like this:

void resetbuttonsize(GtkWindow *window, GdkEvent *event, gpointer data){
    GtkWidget *button1 = data->button;
}

So I could then do something like:

gtk_widget_set_size_request(button1, 40, 40);

Sadly, I can not to this (GtkWidget *button1 = data->button;) because I get the following compiler error:

/media/dysk250/pmanager/testfile/main.cpp|59|error: ‘gpointer {aka void*}’ is not a pointer-to-object type|

Can someone tell me what Im doing wrong? Im newbie with pointers, maybe I could resolve single pointer pointer, but this one is just too much for my brain to understand what is happening and why code I use is wrong.

3 Answers3

1

You need to cast the void* variable into a suitable pointer that can be dereferenced:

GtkWidget *button1 = static_cast<userdata*>(data)->button;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks for your answer, It does work :) So this means for the program to use the data sent to function as it was a "pointer" struct not a normal struct as you program expects it to be? – Karol Szustakowski Aug 29 '16 at 12:20
  • @KarolSzustakowski A pointer of the type `void*` is a *generic* pointer, it can point to anything. At the same time it doesn't have any type information, other than it is a pointer. That why you have to cast it to a specific type. It is commonly used in C code (remember that Gtk is a C toolkit, not C++). – Some programmer dude Aug 29 '16 at 12:22
0

A pointer of the type void* is a generic pointer. You can not do any operations on it without casting it to the original type.

userdata* userData = static_cast<userdata*>(data);
GtkWidget* button1 = userData->button1;
GtkWidget* button2 = userData->button2;
CreativeMind
  • 897
  • 6
  • 19
0

If you are using void * pointer, make sure you cast it to specific pointer type whenever it is necessary, like below in your case.

void resetbuttonsize(GtkWindow *window, GdkEvent *event, gpointer data){
    userdata * data1 = static_cast<userdata*>(data);
    GtkWidget *button1 = data1->button1;
}

Secondly, your structure userdata do not have member button, you must use either button1 or button2

Sandy
  • 159
  • 1
  • 2
  • 15