0

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

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;
}

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

感谢所有意见和建议。

4

1 回答 1

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);
}
于 2010-03-29T02:28:34.860 回答