2014-08-28 102 views
5

我在寫一個C函數,它以ints的Python tuple作爲參數。Python數組到C數組

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} 

EDIT

相反的元組我可以通過與由分隔的數字串的 ';'。例如'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) 
} 

EDIT(液)

我想我已經找到了解決辦法:

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 :) 
    } 

回答

2

使用PyArg_VaParse:https://docs.python.org/2/c-api/arg.html#PyArg_VaParse 它的工作原理與va_list的,在那裏你可以檢索可變數量的參數。

此處瞭解詳情: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

設我知道它是否對你有幫助。

+0

va_list?他只有一個論點。 – 2014-08-28 15:30:56

+0

參數是一個元組,所以你可以使用操作元組的函數... https://docs.python.org/2/c-api/tuple.html 像PyTuple_GetItem和PyTuple_Size 這裏有一個例子這應該有所幫助:http://stackoverflow.com/questions/8001923/python-extension-module-with-variable-number-of-arguments – danielfranca 2014-08-28 15:46:09

+0

謝謝,PyTuple_Size和PyTuple_GetItem是非常有用的:) – 2014-08-28 16:12:23

0

不知道這是你在找什麼,但 你可以寫一個C函數,它使用va_list和va_start來獲取可變數量的參數。 該教程是在這裏:http://www.cprogramming.com/tutorial/c/lesson17.html

+0

來自手冊:「C函數總是有兩個參數,通常命名爲self和args。」 – 2014-08-28 15:26:04