我正在编写一个C函数,它将ints
的Python tuple
作为参数。
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 :)
}
3条答案
按热度按时间lymnna711#
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.
更多信息:http://www.cplusplus.com/reference/cstdarg/va_list/
因为它是一个元组,所以可以使用元组函数:https://docs.python.org/2/c-api/tuple.html类似于PyTuple_Size和PyTuple_GetItem
这里有一个如何使用它的例子:Python extension module with variable number of arguments
如果有帮助就告诉我。
nfg76nw02#
不确定这是不是你要找的,但是你可以用va_list和va_start来写一个C函数,它的参数个数是可变的。http://www.cprogramming.com/tutorial/c/lesson17.html
jbose2ul3#
我想我已经找到了解决办法:
这个答案是由CC BY-SA 3.0下的OP Piotr Dabkowski作为问题Python元组到C数组的edit发布的。