【问题标题】:Pass list as argument to Python C module?将列表作为参数传递给 Python C 模块?
【发布时间】:2011-03-16 06:39:39
【问题描述】:

我找到了this Python C 模块的好例子,其中一个整数作为唯一的参数传递。我怎样才能将 python 列表作为参数传递?

【问题讨论】:

    标签: python c list integration arguments


    【解决方案1】:

    来自http://code.activestate.com/lists/python-list/31841/

    ...
    char * tok;         /* delimiter tokens for strtok */
    int cols;           /* number of cols to parse, from the left */
    
    int numLines;       /* how many lines we passed for parsing */
    char * line;        /* pointer to the line as a string */
    char * token;       /* token parsed by strtok */
    
    PyObject * listObj; /* the list of strings */
    PyObject * strObj;  /* one string in the list */
    
    /* the O! parses for a Python object (listObj) checked
       to be of type PyList_Type */
    if (! PyArg_ParseTuple( args, "O!is", &PyList_Type, &listObj, 
               &cols, &tok )) return NULL;
    
    /* get the number of lines passed to us */
    numLines = PyList_Size(listObj);
    
    /* should raise an error here. */
    if (numLines < 0)   return NULL; /* Not a list */
    

    ...

    /* iterate over items of the list, grabbing strings, and parsing
       for numbers */
    for (i=0; i<numLines; i++){
    
    /* grab the string object from the next element of the list */
    strObj = PyList_GetItem(listObj, i); /* Can't fail */
    
    /* make it a string */
    line = PyString_AsString( strObj );
    
    /* now do the parsing */
    

    Parsing arguments and building values

    【讨论】:

    • colstok 是干什么用的?
    • numLines &lt; 0 检查真的有必要吗?
    【解决方案2】:

    使用O argumentssequence protocol 之一。

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2019-03-02
      • 2012-03-07
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多