How does GObject style construction work?

你离开我真会死。 提交于 2020-02-05 03:22:26

问题


I'm new to Vala and trying to understand how the language works. I usually use script languages like Python or JavaScript.

So, my question is why are there three ways of class constructor definition and how does the GObject style constructor work?

For the best understanding lets make an analogy with python:

Python class definition

class Car(object):
  speed: int

  def __init__(self, speed): # default constructor
    self.speed = speed # property

And Vala

class Car : GLib.Object {
  public int speed { get; construct; }

  // default
  internal Car(int speed) {
    Object(speed: speed)
  }

  construct {} // another way
}

I was reading the Vala tutorial section about GObject style construction, but still do not understand how Object(speed: speed) works and for what construct is needed?


回答1:


Vala was developed as a replacement for the manual effort needed to write GLib based C code.

Since C has no classes in GLib based C code object construction is done in a different way than in say C# or Java.

Here is a fragment of the output of valac -C car.vala for your example code:

Car*
car_construct (GType object_type,
               gint speed)
{
    Car * self = NULL;
    self = (Car*) g_object_new (object_type, "speed", speed, NULL);
    return self;
}

So Vala emits a car_construct function that calls the g_object_new () method. This is the GLib method used to create any GLib based class, by passing its type and construct parameters by name and value arguments one after another, terminated by NULL.

When you don't use construct properties it won't be possible to pass parameters via g_object_new () and you'd have to call the setter, for example:

Car*
car_construct (GType object_type,
               gint speed)
{
    Car * self = NULL;
    self = (Car*) g_object_new (object_type, NULL);
    car_set_speed (self, speed);
    return self;
}

Here car_set_speed () is called instead of passing the value via g_object_new ().

Which one you prefer depends on a few factors. If you do interop with C code often and the C code uses construct parameters, you want to use GObject style construction. Otherwise you are probably fine with the C#/Java style constructors.

PS: The setter is also auto generated by valac and will not only set the property value, but notify any listeners through the g_object_notify () system.



来源:https://stackoverflow.com/questions/59854049/how-does-gobject-style-construction-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!