Question

I'm really new to C -> Python interaction and am currently writing a small app in C which will read a file (using Python to parse it) and then using the parsed information to execute small Python snippets. At the moment I'm feeling very much like I'm reinventing wheels, for example this function:

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

I would really like to do this in a easier/smarter way less prone to memory leaks and errors.

All comments and suggestions are appreciated.

Was it helpful?

Solution

I recommend PySequence_Fast and friends:

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top