【问题标题】:Looking for a smarter way to convert a Python list to a GList?正在寻找一种更智能的方式将 Python 列表转换为 GList?
【发布时间】:2023-03-31 19:35:02
【问题描述】:

我真的是 C -> Python 交互的新手,目前正在用 C 编写一个小应用程序,它将读取一个文件(使用 Python 解析它),然后使用解析的信息来执行小 Python sn-ps。此刻我感觉很像是在重新发明轮子,比如这个函数:

typedef gpointer (list_func)(PyObject *obj);

GList *pylist_to_glist(list_func func, PyObject *pylist)
{
    GList *result = NULL;
    if (func == NULL)
    {
        fprintf(stderr, "No function definied for coverting PyObject.\n");
    }
    else if (PyList_Check(pylist))
    {
        PyObject *pIter = PyObject_GetIter(pylist);
        PyObject *pItem;

        while ((pItem = PyIter_Next(pIter)))
        {
            gpointer obj = func(pItem);
            if (obj != NULL) result = g_list_append(result, obj);
            else fprintf(stderr, "Could not convert PyObject to C object.\n");
            Py_DECREF(pItem);
        }
        Py_DECREF(pIter);
    }
    return result;
}

我真的很想以一种更容易/更智能的方式做到这一点,更不容易出现内存泄漏和错误。

感谢所有 cmets 和建议。

【问题讨论】:

    标签: python c glib python-embedding


    【解决方案1】:

    我推荐PySequence_Fast和朋友们:

    else
    {
        PyObject *pSeqfast = PySequence_Fast(pylist, "must be a sequence");
        Py_ssize_t n = PySequence_Fast_GET_SIZE(pSeqFast);
    
        for(Py_ssize_t i = 0; i < n ; ++i)
        {
            gpointer obj = func(PySequence_Fast_GET_ITEM(pSeqfast, i));
            if (obj != NULL) result = g_list_append(result, obj);
            else fprintf(stderr, "Could not convert PyObject to C object.\n");
        }
        Py_DECREF(pSeqfast);
    }
    

    【讨论】:

    • 是的,这似乎是一个非常好的解决方案 :) 谢谢!
    猜你喜欢
    • 2016-05-11
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 2017-07-03
    相关资源
    最近更新 更多