Python tuple to C array
Asked Answered
E

3

9

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)
}
Englishry answered 28/8, 2014 at 15:13 Comment(0)
T
3

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.

Trieste answered 28/8, 2014 at 15:27 Comment(3)
va_list? he only has one argument.Aforetime
The argument is a tuple, so you can use the functions that manipulate tuples... docs.python.org/2/c-api/tuple.html like PyTuple_GetItem and PyTuple_Size Here there's an example that should help: #8002423Trieste
Thanks, PyTuple_Size and PyTuple_GetItem were very useful :)Englishry
P
0

Not sure if this is what you're looking for, but you could write a C function that takes a variable number of arguments, using va_list and va_start. A tutorial is here: http://www.cprogramming.com/tutorial/c/lesson17.html

Postprandial answered 28/8, 2014 at 15:22 Comment(1)
from the manual: "The C function always has two arguments, conventionally named self and args."Aforetime
T
-1

I think I have 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
    }
}

This answer was posted as an edit to the question Python tuple to C array by the OP Piotr Dabkowski under CC BY-SA 3.0.

Trotskyism answered 22/12, 2022 at 13:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.