g_object_new_with_properties用不了
时间: 2023-07-29 16:14:38 浏览: 102
ehlib_vcl_src_9_3.26
`g_object_new_with_properties` 是 GLib 中用于创建 GObject 的函数之一,它可以接受一个以 `NULL` 结尾的 `GObjectProperty` 数组作为参数,用于设置 GObject 的属性。如果无法使用该函数,可能是因为您没有包含必要的头文件,或者没有正确地链接 GLib 库。
以下是一个简单的示例,演示如何使用 `g_object_new_with_properties` 函数创建一个 GObject:
```c
#include <glib-object.h>
typedef struct _MyObject MyObject;
struct _MyObject {
GObject parent;
guint property1;
gchar *property2;
};
enum {
PROP_0,
PROP_PROPERTY_1,
PROP_PROPERTY_2,
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_PROPERTY_1:
self->property1 = g_value_get_uint (value);
break;
case PROP_PROPERTY_2:
g_free (self->property2);
self->property2 = g_value_dup_string (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_PROPERTY_1:
g_value_set_uint (value, self->property1);
break;
case PROP_PROPERTY_2:
g_value_set_string (value, self->property2);
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_PROPERTY_1] =
g_param_spec_uint ("property1",
"Property 1",
"Description of property 1",
0,
G_MAXUINT,
0,
G_PARAM_READWRITE);
obj_properties[PROP_PROPERTY_2] =
g_param_spec_string ("property2",
"Property 2",
"Description of property 2",
NULL,
G_PARAM_READWRITE);
g_object_class_install_properties (gobject_class,
N_PROPERTIES,
obj_properties);
}
static void my_object_init (MyObject *self)
{
self->property1 = 0;
self->property2 = NULL;
}
int main (int argc, char *argv[])
{
g_type_init ();
GValue property_values[3] = {0, };
g_value_init (&property_values[0], G_TYPE_UINT);
g_value_set_uint (&property_values[0], 42);
g_value_init (&property_values[1], G_TYPE_STRING);
g_value_set_string (&property_values[1], "Hello world");
MyObject *obj = g_object_new_with_properties (MY_TYPE_OBJECT,
property_values);
g_print ("Property 1: %u\n", my_object_get_property1 (obj));
g_print ("Property 2: %s\n", my_object_get_property2 (obj));
g_object_unref (obj);
return 0;
}
```
这个程序定义了一个名为 `MyObject` 的 GObject 子类,包含两个属性 `property1` 和 `property2`,并演示了如何使用 `g_object_new_with_properties` 函数创建该对象。如果您仍然遇到问题,请提供更多的上下文和代码,以便我能够更好地帮助您。
阅读全文