Vala:了解 类 中的结构属性

Vala: Understanding Struct Properties in Classes

我目前正在学习 https://wiki.gnome.org/Projects/Vala/Tutorial 上的 Vala 教程。现在我偶然发现了一个需要进一步解释的部分;在本教程最后的对象属性部分中介绍了结构属性。给出了一个示例来说明如何检索这样的 属性:

struct Color
{
    public uint32 argb;

    public Color() { argb = 0x12345678; }
}

class Shape: GLib.Object
{
    public Color c { get; set; default = Color(); }
}

int main()
{
    Color? c = null;
    Shape s = new Shape();
    s.get("c", out c);
}

教程指出:"This way, c is an reference instead of an instance of Color on stack. What you passed into s.get() is Color ** instead of Color *."

我的问题是关于上面的陈述。首先,有人可以详细说明 "What you passed into s.get() is Color ** instead of Color *." 的含义吗?另外,这是否意味着以下

int main()
{
    Shape s = new Shape();
    Color c = s.c;
}

导致 s.c 被分配给 c?

编辑:我运行上面的例子在valac -C structs.valamain 方法的相关 C 等价物是

gint _vala_main (void) {
    gint result = 0;
    Color* c = NULL;
    Shape* s = NULL;
    Shape* _tmp0_ = NULL;
    c = NULL;
    _tmp0_ = shape_new ();
    s = _tmp0_;
    g_object_get ((GObject*) s, "c", &c, NULL);
    result = 0;
    _g_object_unref0 (s);
    _color_free0 (c);
    return result;
}

valac 将 Vala 代码编译成 C 代码,然后由 C 编译器(通常是 GCC)编译成目标格式(例如目标文件、库或可执行文件)。

所以本教程在说 Color** 时所谈论的是生成的 C 代码会将 pointer to a pointer to a Color struct 传递给函数(在生成的 C 代码中为 gobject_get ).

结构是 C 和 Vala* 中的值类型,这意味着它们的所有内存都是在赋值时复制的。 Vala 中的 Color?(a nullable Color)等同于 C 中的 Color*(a pointer to Color

Vala 也将 refout 参数转换为 C 中的指针,因此在调用 outref 具有可为空结构变量的参数。

C 的类型不如 Vala 强,这就是为什么许多 Vala 构造最终成为 C 中的指针的原因。C 使用指针来声明可选事物、引用、按引用调用参数、数组/字符串,链表和其他一些更晦涩的东西(比如函数指针和泛型)。

关于你的第二个问题:当直接赋值给一个结构变量时,会生成一个副本*。

* 这解释了何时在 Vala 和 C 级别进行复制。