Passing a Python list to C function using the Python/C API

前端 未结 2 1201
花落未央
花落未央 2020-12-17 04:20

I\'ve recently started using the Python/C API to build modules for Python using C code. I\'ve been trying to pass a Python list of numbers to a C function without success:

相关标签:
2条回答
  • 2020-12-17 04:43

    This example will show you how to

    1. Get the length of the list
    2. Allocate storage for an array of double
    3. Get each element of the list
    4. Convert each element to a double
    5. Store each converted element in the array

    Here is the code:

    #include "Python.h"
    
    int _asdf(double pr[], int length) {
        for (int index = 0; index < length; index++)
            printf("pr[%d] = %f\n", index, pr[index]);
        return 0;
    }
    
    static PyObject *asdf(PyObject *self, PyObject *args)
    {
        PyObject *float_list;
        int pr_length;
        double *pr;
    
        if (!PyArg_ParseTuple(args, "O", &float_list))
            return NULL;
        pr_length = PyObject_Length(float_list);
        if (pr_length < 0)
            return NULL;
        pr = (double *) malloc(sizeof(double *) * pr_length);
        if (pr == NULL)
            return NULL;
        for (int index = 0; index < pr_length; index++) {
            PyObject *item;
            item = PyList_GetItem(float_list, index);
            if (!PyFloat_Check(item))
                pr[index] = 0.0;
            pr[index] = PyFloat_AsDouble(item);
        }
        return Py_BuildValue("i", _asdf(pr, pr_length));
    }
    

    NOTE: White space and braces removed to keep code from scrolling.

    Test program

    import asdf
    print asdf.asdf([0.7, 0.0, 0.1, 0.0, 0.0, 0.2])
    

    Output

    pr[0] = 0.700000
    pr[1] = 0.000000
    pr[2] = 0.100000
    pr[3] = 0.000000
    pr[4] = 0.000000
    pr[5] = 0.200000
    0
    
    0 讨论(0)
  • 2020-12-17 04:43

    Would this do to properly free memory?

    PyObject *res;
    res = Py_BuildValue("i", _asdf(pr, pr_length));
    free(pr);
    return res;
    
    0 讨论(0)
提交回复
热议问题