-1

I'm trying to get a list as an argument in a C extension in Python, the function and the wrapper (Function's table is omitted):

#include <Python.h>

int MyFunction(int a_triplet[]){

    printf("%i\n", a_triplet[0]);

    return 0;    
}

static PyObject* any_function(PyObject* self, PyObject* args)
{

    PyObject *lst;

    if (!PyArg_ParseTuple(args, "O", &lst))
        return NULL;

    return Py_BuildValue("[i]", MyFunction(lst)); // Returns error
}

I'm a bit lost in the last line:

return Py_BuildValue("[i]", MyFunction(lst));

And in the Python function I have this:

print (Module.any_function([67, 93, 56]))

How can I get the list passed in Python to the C extension? I'm a lost because if I write a function and a wrapper to receive an integer, works perfectly:

#include <Python.h>

int MyFunction(int n){

    printf("%i", n);

    return 0;    
}

static PyObject* alice_bob(PyObject* self, PyObject* args)
{

    int n;

    if (!PyArg_ParseTuple(args, "i", &n))
        return NULL;

    return Py_BuildValue("i", MyFunction(n));
}
dfrojas
  • 673
  • 1
  • 13
  • 32
  • Do you mean a Python "list"? Tuples? Your syntax seems to indicate so. There are some other types which actually are arrays (numpy types, the 'array' module in Python, etc.). Be precise, please. – Max Oct 03 '18 at 16:04
  • Hi @Max A list. I have edited my question – dfrojas Oct 03 '18 at 16:09
  • http://idownvotedbecau.se/unclearquestion What is your exact question? How to build list with PyBuildValue? How to pass list to your function? How to convert PyList to C array? – ivan_pozdeev Oct 03 '18 at 16:21
  • @ivan_pozdeev My question is explicit: "How can I get the list passed in Python to the C extension?" Actually, I explain why I'm confused because with integers works fine. If you consider a downvote it's ok. But other readers have understand the question – dfrojas Oct 03 '18 at 16:25
  • @dfrojas then you already have: your `lst` is a `PyList`, and I don't see the problem. If your real question is rather "how should I _work_ with what I've got", then you should be asking that, and specify what exactly you're trying to do. – ivan_pozdeev Oct 03 '18 at 16:28

1 Answers1

0
  • The Numpy API has a function PyArray_Mean that accomplishes what you're trying to do :

    static PyObject *func1(PyObject *self, PyObject *args) {
        PyArrayObject *X, *meanX;
        int axis;
        PyArg_ParseTuple(args, "O!i", &PyArray_Type, &X, &axis);
        meanX = (PyArrayObject *) PyArray_Mean(X, axis, NPY_DOUBLE, NULL);
        return PyArray_Return(meanX);
    }