注册 GLib.Value 的类型
在前面的示例中,Value.strdup_contents 将 GLib.DateTime 打印为指针地址。你可以注册将值转换为所需类型的函数。首先,创建一个具有此签名的函数 :
static void datetime_to_string (Value src_value, ref Value dest_value) {
DateTime dt = (DateTime)src_value;
dest_value.set_string (dt.to_string());
}
然后使用 Value.register_transform_func 注册此函数 :
Value.register_transform_func (typeof (DateTime), typeof (string), datetime_to_string);
现在 GObject 可以将任何 DateTime 对象转换为字符串值。
完整的例子:
static void datetime_to_string (Value src_value, ref Value dest_value) {
DateTime dt = (DateTime)src_value;
dest_value.set_string (dt.to_string());
}
static void print_value (Value val) {
print ("value-type : %s\n", val.type().name());
print ("value-content : %s\n\n", val.strdup_contents());
}
public static void main (string[] args) {
print_value (new DateTime.now_local());
Value.register_transform_func (typeof (DateTime), typeof (string), datetime_to_string);
print_value (new DateTime.now_local());
}
value-type : GDateTime
value-content : ((GDateTime*) 0x560337def040)
value-type : GDateTime
value-content : 2017-04-20T18:40:20+0200