Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tuple to C array

I am writing a C function that takes a Python tuple of ints as an argument.

static PyObject* lcs(PyObject* self, PyObject *args) {
    int *data;
    if (!PyArg_ParseTuple(args, "(iii)", &data)) {
        ....
    }
}

I am able to convert a tuple of a fixed length (here 3) but how to get a C array from a tuple of any length?

import lcs
lcs.lcs((1,2,3,4,5,6)) #<- C should receive it as {1,2,3,4,5,6}

EDIT

Instead of a tuple I can pass a string with numbers separated by ';'. Eg '1;2;3;4;5;6' and separate them to the array in C code. But I dont think it is a proper way of doing that.

static PyObject* lcs(PyObject* self, PyObject *args) {
    char *data;
    if (!PyArg_ParseTuple(args, "s", &data)) {
        ....
    }
    int *idata;
    //get ints from data(string) and place them in idata(array of ints)
}

EDIT (SOLUTION)

I think I've found a solution:

static PyObject* lcs(PyObject* self, PyObject *args) {
    PyObject *py_tuple;
    int len;
    int *c_array;
    if (!PyArg_ParseTuple(args, "O", &py_tuple)) {
      return NULL;
    }
    len = PyTuple_Size(py_tuple);
    c_array= malloc(len*4);
    while (len--) {
        c_array[len] = (int) PyInt_AsLong(PyTuple_GetItem(py_tuple, len));
   //c_array is our array of ints :)
    }
like image 666
Piotr Dabkowski Avatar asked Aug 28 '14 15:08

Piotr Dabkowski


1 Answers

Use PyArg_VaParse: https://docs.python.org/2/c-api/arg.html#PyArg_VaParse It works with va_list, where you can retrieve a variable number of arguments.

More info here: http://www.cplusplus.com/reference/cstdarg/va_list/

And as it's a tuple you can use the tuple functions: https://docs.python.org/2/c-api/tuple.html like PyTuple_Size and PyTuple_GetItem

Here's there's a example of how to use it: Python extension module with variable number of arguments

Let me know if it helps you.

like image 109
dfranca Avatar answered Sep 27 '22 20:09

dfranca