函数参数的GTK +类型转换风格

时间:2010-10-04 08:59:22

标签: c gtk

在GTK +调用中,在传递参数之前,参数应该(但不必)从GtkWidget转换为函数所需的最具体的类。例如,有时候我会看到

some_call(GTK_WINDOW(window));

而其他时候,我看到了

some_call((GtkWindow *) window);

有什么区别?

3 个答案:

答案 0 :(得分:7)

GTK_WINDOW是执行演员表的宏。

As seen here

#define GTK_WINDOW(obj)  (GTK_CHECK_CAST ((obj), GTK_TYPE_WINDOW, GtkWindow))

Again

#define GTK_CHECK_CAST G_TYPE_CHECK_INSTANCE_CAST

and

#define G_TYPE_CHECK_INSTANCE_CAST(instance, g_type, c_type) (_G_TYPE_CIC ((instance), (g_type), c_type))

which is...

#define _G_TYPE_CIC(ip,gt,ct)    \
    ((ct*) g_type_check_instance_cast ((GTypeInstance*) ip, gt))

g_type_check_instance_cast can be found here

的代码
GTypeInstance*
g_type_check_instance_cast (GTypeInstance *type_instance,
                            GType          iface_type)
{
  if (type_instance)
    {
      if (type_instance->g_class)
        {
          TypeNode *node, *iface;
          gboolean is_instantiatable, check;

          node = lookup_type_node_I (type_instance->g_class->g_type);
          is_instantiatable = node && node->is_instantiatable;
          iface = lookup_type_node_I (iface_type);
          check = is_instantiatable && iface && type_node_conforms_to_U (node, iface, TRUE, FALSE);
          if (check)
            return type_instance;

          if (is_instantiatable)
            g_warning ("invalid cast from `%s' to `%s'",
                       type_descriptive_name_I (type_instance->g_class->g_type),
                       type_descriptive_name_I (iface_type));
          else
            g_warning ("invalid uninstantiatable type `%s' in cast to `%s'",
                       type_descriptive_name_I (type_instance->g_class->g_type),
                       type_descriptive_name_I (iface_type));
        }
      else
        g_warning ("invalid unclassed pointer in cast to `%s'",
                   type_descriptive_name_I (iface_type));
    }

  return type_instance;
}

答案 1 :(得分:2)

第一个是一个宏,可以测试是否可以进行强制转换并执行强制转换。这是GTK版本/类型安全演员的尝试。你应该使用那个。

答案 2 :(得分:-3)

GTK_WINDOW()只是一个看起来像这样的宏:

#define GTK_WINDOW(a) ((GtkWindow*)a)

这与你自己做一个明确的演员是一样的,你在帖子中应该的两个陈述是相同的。