Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make pointers compatible in a new struct?

I am trying 'inherit' a GtkWidget. I could inherit any other widget like GtkWindow etc and implement its methods in its own file. I am then going to load the new widget with a function which returns the widget like so return g_object_new(....

The code works fine but I get incompatible pointer type warning in the struct init function.

class.h

#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED

#include <gtk/gtk.h>
#define CLASS_NAME_TYPE (class_name_get_type())
G_DECLARE_FINAL_TYPE(ClassName, class_name, CLASS, NAME, GtkWidget)

ClassName *class_name_new();

#endif // CLASS_H_INCLUDED

class.c

#include "class.h"

struct _ClassName
{
  GtkWidget parent;
};

G_DEFINE_TYPE(ClassName, class_name, GTK_TYPE_WIDGET);

static void class_name_init(ClassName *self)
{
    gtk_widget_set_name(self, "Widget");
}

static void class_name_class_init(ClassNameClass *klass)
{

}

ClassName *class_name_new()
{
    return g_object_new(CLASS_NAME_TYPE, /* "foo", bar ,*/ NULL);
}

In the function static void class_name_init(ClassName *self), I want to use the pointer self like so

gtk_widget_set_name(self, "Widget");

This is where I have compatible pointer type. gtk_widget_set_name() is expecting a type GtkWidget as an input but the init function has the type ClassName.

Gtk knows ClassName is the same type as GtkWidget hence the code works but is there anyway to fix the code so that the compiler doesn't think its a mistake

like image 819
Bret Joseph Antonio Avatar asked Jul 04 '26 16:07

Bret Joseph Antonio


1 Answers

In general, you should use cast operator to avoid compiler warnings, assuming that self is a pointer:

gtk_widget_set_name((GtkWidget*)self, "Widget");
like image 64
risbo Avatar answered Jul 06 '26 08:07

risbo