【发布时间】:2014-08-28 15:13:24
【问题描述】:
我正在编写一个 C 函数,它将 Python tuple 或 ints 作为参数。
static PyObject* lcs(PyObject* self, PyObject *args) {
int *data;
if (!PyArg_ParseTuple(args, "(iii)", &data)) {
....
}
}
我可以转换一个固定长度的元组(这里是 3 个),但是如何从任意长度的 tuple 中得到一个 C array?
import lcs
lcs.lcs((1,2,3,4,5,6)) #<- C should receive it as {1,2,3,4,5,6}
编辑
我可以传递一个由“;”分隔的带有数字的字符串,而不是一个元组。例如 '1;2;3;4;5;6' 并将它们分隔到 C 代码中的数组中。但我不认为这是一种正确的做法。
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)
}
编辑(解决方案)
我想我找到了解决办法:
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 :)
}
【问题讨论】: