Sto scrivendo una funzione C che prende un Python tuple
di ints
come argomento.Python tuple to C array
static PyObject* lcs(PyObject* self, PyObject *args) {
int *data;
if (!PyArg_ParseTuple(args, "(iii)", &data)) {
....
}
}
sono in grado di convertire una tupla di una lunghezza fissa (qui 3), ma come ottenere una C array
da un tuple
di qualsiasi lunghezza?
import lcs
lcs.lcs((1,2,3,4,5,6)) #<- C should receive it as {1,2,3,4,5,6}
EDIT
posto di una tupla posso passare una stringa con numeri separati da ';'. Per esempio '1; 2; 3; 4; 5; 6' e separali nell'array nel codice C. Ma non penso che sia un modo corretto per farlo.
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 (soluzione)
Credo di aver trovato una soluzione:
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 :)
}
va_list? ha solo un argomento. –
L'argomento è una tupla, in modo da poter utilizzare le funzioni che manipolano le tuple ... https://docs.python.org/2/c-api/tuple.html come PyTuple_GetItem e PyTuple_Size Qui c'è un esempio che dovrebbe aiutare: http://stackoverflow.com/questions/8001923/python-extension-module-with-variable-number-of-arguments – danielfranca
Grazie, PyTuple_Size e PyTuple_GetItem sono stati molto utili :) –