gobject的g_object_new_with_properties使用实例
时间: 2023-07-31 13:04:30 浏览: 233
g_object_new_with_properties函数可以用于创建一个GObject实例,并且在实例化对象时可以设置该对象的属性值。它的原型如下:
```c
gpointer g_object_new_with_properties (GType object_type,
guint n_properties,
GObjectConstructParam *properties);
```
其中,object_type是要实例化对象的类型。n_properties是要设置的属性数量。properties是一个GObjectConstructParam类型的数组,用于保存要设置的属性信息。
下面是一个使用g_object_new_with_properties函数创建GObject实例并设置属性的示例代码:
```c
#include <glib-object.h>
typedef struct _MyObject MyObject;
struct _MyObject {
GObject parent_instance;
gchar *name;
gint age;
};
enum {
PROP_NAME = 1,
PROP_AGE,
N_PROPERTIES
};
static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
static void my_object_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
MyObject *self = MY_OBJECT (object);
switch (property_id) {
case PROP_NAME:
g_free (self->name);
self->name = g_value_dup_string (value);
break;
case PROP_AGE:
self->age = g_value_get_int (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void my_object_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
MyObject *self = MY_OBJECT (object);
switch (property_id) {
case PROP_NAME:
g_value_set_string (value, self->name);
break;
case PROP_AGE:
g_value_set_int (value, self->age);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
static void my_object_class_init (MyObjectClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->set_property = my_object_set_property;
gobject_class->get_property = my_object_get_property;
obj_properties[PROP_NAME] =
g_param_spec_string ("name",
"Name",
"The name of the object",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT);
obj_properties[PROP_AGE] =
g_param_spec_int ("age",
"Age",
"The age of the object",
0,
G_MAXINT,
0,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT);
g_object_class_install_properties (gobject_class,
N_PROPERTIES,
obj_properties);
}
static void my_object_init (MyObject *self)
{
self->name = NULL;
self->age = 0;
}
int main (void)
{
MyObject *obj = g_object_new_with_properties (MY_TYPE_OBJECT,
2,
"name", "Tom",
"age", 18);
g_object_unref (obj);
return 0;
}
```
在上面的示例代码中,我们定义了一个MyObject类型的GObject子类,并且添加了两个属性:name和age。在类初始化时,我们使用g_object_class_install_properties函数将这两个属性安装到MyObject类中。在对象初始化时,我们将这两个属性的默认值分别设置为NULL和0。
在main函数中,我们使用g_object_new_with_properties函数创建一个MyObject实例,并且设置name属性为"Tom",age属性为18。最后,我们使用g_object_unref函数释放该实例。
需要注意的是,在使用g_object_new_with_properties函数创建对象时,属性名称和属性值必须成对出现,并且属性名称必须是字符串类型。在示例代码中,我们使用"name"和"age"作为属性名称。
阅读全文