[Python] PyArray_SimpleNewFromData

Discussão em 'Python' iniciado por Stack, Abril 13, 2025.

  1. Stack

    Stack Membro Participativo

    So I am trying to write a C function that accepts a numpy array object, extracts the data, does some manipulations and returns another c array as a numpy array object. Everything works seamlessly and I use python wrappers which help easy manipulation on the python side. However, I am facing a memory leak. I have an output pointer of doubles that I malloc-ed and which I wrap into a Python array object just before returning it to the calling python function,

    PyObject *arr;
    int nd = 2;
    npy_intp dims[] = {5, 10};
    double *data = some_function_that_returns_a_double_star(x, y, z);

    arr = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, (void *)data);
    return arr;


    However, this creates a memory leak, because data is never freed and I did some googling to find that this is a problem in such applications and solution is non-trivial. The most helpful resource that I found on this is given here. I could not implement the destructor that this page talks about from the given example. Can someone help me with this? More concretely I am looking for something like,

    PyObject *arr;
    int nd = 2;
    npy_intp dims[] = {5, 10};
    double *data = some_function_that_returns_a_double_star(x, y, z);

    arr = PyArray_SimpleNewFromData(nd, dims, NPY_DOUBLE, (void *)data);
    some_destructor_that_plug_memLeak_due_to_data_star(args);
    return arr;


    Continue reading...

Compartilhe esta Página