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)
}

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

va_list? he only has one argument.
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: stackoverflow.com/questions/8001923/…
Thanks, PyTuple_Size and PyTuple_GetItem were very useful :)
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

1 Comment

from the manual: "The C function always has two arguments, conventionally named self and args."
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.