Pregunta

Soy realmente nuevo en la interacción C -> Python y actualmente estoy escribiendo una pequeña aplicación en C que leerá un archivo (usando Python para analizarlo) y luego usando la información analizada para ejecutar pequeños fragmentos de Python. Por el momento me siento mucho como si estuviera reinventando ruedas, por ejemplo, esta función:

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

Realmente me gustaría hacer esto de una manera más fácil/inteligente menos propensa a las filtraciones y errores de memoria.

Se aprecian todos los comentarios y sugerencias.

¿Fue útil?

Solución

yo recomiendo PySECHENCE_FAST y amigos:

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top