How to say type cast from function

While training on GTK +, I came across an example code that looks like this:

gtk_misc_set_alignment (GTK_MISC (label), 0, 0); 

all authors code has a space between the function and (), but also type receptions. Obviously gtk_misc_set_alignment () is a function, but how can I tell if GTK_MISC (label) is a function or type?

Sorry for the noob question, I'm a noob programmer, Thanks in advance

+4
source share
4 answers

In fact, GTK_MISC is a macro that hides the "classic" type C. Perhaps something like:

 #define GTK_MISC(p) ((GtkMisc *)(p)) 

Instead, you can simply write:

 gtk_misc_set_alignment ((GtkMisc *) label, 0, 0); 

I don’t know exactly why GTK provides such macros, maybe they like to "emulate" the "functional" listing provided by C ++.


Edit

Ok, maybe I get it. I have not found specific documentation for GTK_MISC , but it looks like G_OBJECT , which says:

 #define G_OBJECT(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), G_TYPE_OBJECT, GObject)) 

Inserts a GObject or derived pointer into a pointer (GObject*) . Depending on the current debugging level, this function may call certain runtime checks to identify invalid translations.

Thus, it is likely that GTK_MISC also does some runtime checks on the pointer to see if it can actually be sent to GtkMisk * . You could say that this is somewhat of the concept of dynamic_cast in C ++.

+9
source

Type casting is performed with the type inside the parenthesis

 ( type ) object // typecast identifier ( argument ) // function call 
+5
source

In C, type(value) not valid. This syntax is C ++.

+4
source

GLib, and therefore a system like GTK is slightly different from a system like C. GLib is developed in C, and therefore it cannot have real classes, like in C ++, C # or Java. Therefore, they need to somehow imitate. Each object is actually a structure (in this case, the _GtkMisc structure), which has a class field that is initialized when a type (class) is registered. Type input macros check this field value, and if the "object" is inherited from the requested type (in this case, from GtkMisc), it is "assigned" to this. If not, this will give you an error, so if you are not sure, you can check this with the GTK_IS _ * () macros, for example

 if (GTK_IS_MISC(label)) gtk_misc_set_alignment(label); 

In the second part, the spaces before the braces are part of the coding standards of the Gnome team, which, to my knowledge, are derived from the GNU coding standards.

0
source

Source: https://habr.com/ru/post/1399218/


All Articles