Reputation: 5939
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)
}
Upvotes: 9
Views: 5354
Reputation: 31730
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.
Upvotes: -1
Reputation: 5322
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.
Upvotes: 3
Reputation: 37
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
Upvotes: 0