Python tuple for array C

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

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

I can convert a tuple of a fixed length (here 3), but how to get a C array from a tuple 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 ';'. For example, '1; 2; 3; 4; 5; 6 'and split them into an array in C code. But I don't think this is the right way to do this.

 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 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 :) } 
+5
source share
2 answers

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

Further information here: http://www.cplusplus.com/reference/cstdarg/va_list/

And as a tuple, you can use the set functions: https://docs.python.org/2/c-api/tuple.html , for example PyTuple_Size and PyTuple_GetItem

Here's an example of how to use it: Python expander with a variable number of arguments

Let me know if this helps you.

+2
source

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

0
source

Source: https://habr.com/ru/post/1201341/


All Articles