2013-03-11 47 views
0

我正在爲python編寫C擴展。將C對象添加到Python列表並將C對象的列表返回給python

我想知道如何使用PyList_SetItem將C對象添加到python列表中。 例如,

我有一個C對象。

Atom *a = (Atom *)(PyTuple_GET_ITEM(tmp2, 0)); 

我做了一個清單:

PyObject* MyList = PyList_New(3); 

我不知道第三個參數必須在下面的語句是什麼。

PyObject_SetItem(MyList, 0, a); 

另外我該如何返回這個C對象列表爲Python。

回答

2

的第三個參數PyList_SetItem是要添加到列表中,這通常是從C型轉換,如在這個簡單的例子Python的對象:

/* This adds one to each item in a list. For example: 
     alist = [1,2,3,4,5] 
     RefArgs.MyFunc(alist) 
*/ 
static PyObject * MyFunc(PyObject *self, PyObject *args) 
{ 
    PyObject * ArgList; 
    int i; 

    PyArg_ParseTuple(args, "O!", &PyList_Type, &ArgList)); 

    for (i = 0; i < PyList_Size(ArgList); i++) 
    { 
     PyObject * PyValue; 
     long iValue; 

     PyValue = PyList_GetItem(ArgList, i); 

     /* Add 1 to each item in the list (trivial, I know) */ 
     iValue = PyLong_AsLong(PyValue) + 1; 

     /* SETTING THE ITEM */ 
     iRetn = PyList_SetItem(ArgList, i, PyLong_FromLong(iValue)); 

     if (iRetn == -1) Py_RETURN_FALSE; 
    } 

    Py_RETURN_TRUE; 
} 

PyObject_SetItem是相似的。區別在於PyList_SetItem是盜取的參考,但PyObject_SetItem只是借用它。 PyObject_SetItem不能與不可變對象一起使用,如元組。

+0

如果我想將C對象(Atom)添加到列表中,PyLong_FromLong的等效函數是什麼? – user2117235 2013-03-12 14:35:01