如何在 Python 中使用 GLib.Array?

Men*_*hak 5 python glib python-2.7

我正在为 Rhythmbox 编写一个插件,其中引发信号传入一个类型为 的对象GArrayGLib Arrays的文档向我展示了一些我感兴趣但无法访问的方法。

例如,g_array_index可以为我获取GArray 中的第 n 个项目,但我无法调用它。GArray 对象也没有向我展示任何有用的方法。

要了解我的意思,请在 Python 控制台中执行此操作:

from gi.repository.GLib import Array
x = Array()
dir(x)
Run Code Online (Sandbox Code Playgroud)

这是 dir(x) 的输出

['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__gtype__', '__hash__', '__info__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_free_on_dealloc', 'copy', 'data', 'len']
Run Code Online (Sandbox Code Playgroud)

我看到那里没有从数组中读取的方法,也没有关于g_array_indexGLib Arrays 文档页面上提到的任何方法或任何其他方法。我也试过

    for a in x:
        print a
Run Code Online (Sandbox Code Playgroud)

并且

list(x)
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

TypeError: 'Array' object is not iterable
Run Code Online (Sandbox Code Playgroud)

尝试 x[0] 给出了这个:

TypeError: 'Array' object does not support indexing
Run Code Online (Sandbox Code Playgroud)

len属性给出了预期的数组长度。

data属性给出了这样的

在此处输入图片说明

我如何使用我正在传递的这个 GLib.Array?

我正在运行 Python 2.7.4

mat*_*ias 0

GArray没有正确注释/导出,因此它不会像您期望的那样映射到 Python 对象。事实上,您可以使用最后的 C 代码片段检查到底导出了什么以及 Python 模块将看到什么。

info_type = 3 [3 == struct]
n_fields = 2, n_methods = 0
Run Code Online (Sandbox Code Playgroud)

如您所见,仅导出两个字段(len和)。data所以,回答你的问题:到目前为止你还不能真正使用GLib.ArrayPython。

这是代码:

#include <girepository.h>

int
main (int argc, char const* argv[])
{
    GIBaseInfo *info;
    GIStructInfo *struct_info;
    GITypelib *typelib;
    GIInfoType info_type;

    typelib = g_irepository_require (NULL, "GLib", NULL, 0, NULL);
    info = g_irepository_find_by_name (NULL, "GLib", "Array");
    info_type = g_base_info_get_type(info);

    g_print ("info_type = %i [3 == struct]\n", info_type);

    struct_info = (GIStructInfo *) info;

    g_print ("n_fields = %i, n_methods = %i\n",
             g_struct_info_get_n_fields (struct_info),
             g_struct_info_get_n_methods (struct_info));

    g_base_info_unref (info);
    g_typelib_free (typelib);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)